over 3 years ago

系統:

Mac OS X Yosemite 10.10
Ruby 2.1.4
Rails 4.1.7

相關連結

Rspec Rails ( https://github.com/rspec/rspec-rails )
Factory Girl Rails ( https://github.com/thoughtbot/factory_girl_rails )
Capybara ( https://github.com/jnicklas/capybara )
Database Cleaner ( https://github.com/DatabaseCleaner/database_cleaner )
Rack Session Access ( https://github.com/railsware/rack_session_access )

設定步驟如下

1. Gemfile 設定

添加必要的 gem 套件至 Gemfile 檔中

# Rspec testing framework
group :development, :test do
  gem 'rspec-rails', '~> 3.0.0'
  gem 'factory_girl_rails'
  gem 'capybara'
  gem 'database_cleaner'
  gem 'rack_session_access'
end
bundle install
rails generate rspec:install

Specs can also be run via rake spec, though this command may be slower to start than the rspec command.
In Rails 4, you may want to create a binstub for the rspec command so it can be run via bin/rspec:

bundle binstubs rspec-core

2. 修改 rails_helper.rb

...
require 'rspec/rails'
require 'capybara/rspec'
require 'database_cleaner'
...
config.use_transactional_fixtures = false
...

3. 新增 rspec/support/ 底下的檔案

database_cleaner.rb

RSpec.configure do |config|
  config.before do
    DatabaseCleaner.strategy = :truncation
    DatabaseCleaner.start
  end
  config.after(:each) do
    DatabaseCleaner.clean
  end
end

devise.rb (如果有使用 gem: Devise)

RSpec.configure do |config|
  config.include Devise::TestHelpers, type: :controller
end

factory_girl.rb

RSpec.configure do |config|
  config.include FactoryGirl::Syntax::Methods
  config.before(:suite) do
    FactoryGirl.lint
  end
end

paperclip.rb (如果有使用 gem: Paperclip)

require "paperclip/matchers"

RSpec.configure do |config|
  config.include Paperclip::Shoulda::Matchers
  config.after(:suite) do
    FileUtils.rm_rf(Dir["#{Rails.root}/spec/test_files/"])
  end
end

render_views.rb (使 controller 在測試時自動 render 相對應的 views)

RSpec.configure do |config|
  config.render_views
end

4. 新增 spec/factories.rb (管理控制 FactoryGirl 的資料)

# example

FactoryGirl.define do
  factory :user do
    username 'mercicc'
    email 'mercicc.team@gmail.com'
    password 'password'
    confirmed_at Time.now
  end
end

5. 自動生成 spec 檔案

用 rails 生成 controller 或 model 會自動生成相對應的 _spec 檔案

6. 手動生成 spec 檔案

# example

rails generate rspec:model widget

The same generator pattern is available for all specs:

  • scaffold
  • model
  • controller
  • helper
  • view
  • mailer
  • observer
  • integration
  • feature
  • job ## 7. 取消執行 rspec 時的一堆 warning rspec 安裝時預設會有 warnning 提示,可將 .rspec 中的 --warnings 去除即可。 ## 8. 測試顯示內容
    rspec -fd
    rspec -fd spec/features/*
    
    ## 9. 移除 test 資料夾
← RailsAdmin + Devise + Cancan - 基礎安裝篇 OmniAuth with Facebook & GitHub →
 
comments powered by Disqus