Yuto Blog

Yuto Blog

【Ruby on Rails】RSpecとFactoryBotとShoulda MatchersとCapybaraを導入メモ

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

Spring設定

Gemfile
group :test do
  gem 'spring-commands-rspec'
end
spring binstub rspec

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))
Updated by Yuto at 2022-09-19 06:00
0
Like this article
Le Minh Thien Toan

Tác giả:Yuto Yasunaga

Xin chào các bạn. Mình là kỹ sư IT đang làm việc ở Nhật Bản. Mình tạo blog này để chia sẻ về cuộc sống và những kinh nghiệm trong quá trình học tập và làm việc.
Hy vọng bài viết này sẽ có ích cho bạn.