DEV Community

n350071🇯🇵
n350071🇯🇵

Posted on • Updated on

making complex test data in Capybara

🦄 First, Notes

This technique is not actually only for the Capybara testing, but also for RSpec testing. However, the main use case is Capybara.

🤔 Situation

You need to prepare complex test data that is for multiple tests.

It seems to be too complex for Factorybot. But, It seems to be easy with UI manipulations.

👍 Solution

You can use a module and include it, call it from before {} block.

#rails_helper.rb
Dir[Rails.root.join('spec/rails_helpers/**/*.rb')].each { |f| require f }
# spec/rails_helpers/book_operation_scripts.rb
module BookOperationScripts
  def create_published_book(author, options = {})
    click_on('publish a new book')
    fill_in 'v2_book[author]', with: options.fetch(:name, 'n350071')
    fill_in 'v2_book[title]', with: options.fetch(:name, 'enjoy ruby')
    fill_in 'v2_book[price]', with: '8'
    # ...
    page.execute_script("$('form#publish-form').submit()")
  end
end
# spec/v2/feature/books_spec.rb
require 'rails_helper'

feature 'book/', js: true do
  include BookOperationScripts
  let(:author){ create(:v2_author) }
  before do
    create_v2_published_book(author)
  end
end

🔗 Parent Note

Top comments (0)