RSpec設定
Gemfile
group :test do
gem 'rspec-rails'
end
rails g rspec:install
.rspec
--require spec_helper
--format documentation
config/application.rb
config.generators do |g|
g.test_framework :rspec,
fixtures: false,
controller_specs: false,
view_specs: false,
helper_specs: false,
decorator_specs: false,
routing_specs: false
end
Spring設定
Gemfile
group :test do
gem 'spring-commands-rspec'
end
spring binstub rspec
config/environments/test.rb
config.cache_classes = false
FactoryBot設定
Gemfile
group :test do
gem 'factory_bot_rails'
end
spec/support/factory_bot.rb
RSpec.configure do |config|
config.include FactoryBot::Syntax::Methods
end
spec/rails_helper.rb
require "support/factory_bot"
config.before(:all) do
FactoryBot.reload
end
Shoulda Matcher設定
Gemfile
group :test do
gem 'shoulda-matchers'
end
spec/support/shoulda_matchers.rb
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :rails
end
end
spec/rails_helper.rb
require "support/shoulda_matchers"
FFaker設定
Gemfile
group :test do
gem 'ffaker'
end
Fuubar設定
Gemfile
group :test do
gem 'fuubar'
end
.rspec
--format Fuubar
--color
system spec設定
Gemfile
group :test do
gem 'capybara'
gem 'webdrivers'
end
spec/rails_helper.rb
require 'capybara/rspec'
require 'support/capybara'
spec_support/capybara.rb
RSpec.configure do |config|
# Delete screenshot files before testing
FileUtils.rm_rf(Dir[Rails.root.join('tmp/screenshots/*')], secure: true)
# Show screenshot when fail
ENV['RAILS_SYSTEM_TESTING_SCREENSHOT'] = 'inline'
# Driver setup
config.before(:each, type: :system) do
driven_by :selenium_chrome_headless
end
end
Capybara.register_driver :selenium_chrome_headless do |app|
options = Selenium::WebDriver::Chrome::Options.new
%w[
headless
window-size=1600x900
no-sandbox
disable-gpu
].each { |arg| options.add_argument(arg) }
Capybara::Selenium::Driver.new(app, browser: :chrome, options: options)
end
system specでユーザーをログインする
Gemfile
group :test
gem 'rack_session_access'
end
config/environments/test.rb
config.middleware.use RackSessionAccess::Middleware
spec/rails_helper.rb
require 'rack_session_access/capybara'
ユーザーIDのセッションを設定する:
xxx_spec.rb
page.set_rack_session(user_id: user.id)
# deviseを使う場合:
page.set_rack_session('warden.user.user.key' => User.serialize_into_session(user))