Faster Tests With Capybara and Request Specs

Here’s a cool trick to improve the performance of your test suite: write more request specs and fewer system specs (yes, you can use them for more than API testing).

Rails is very good at CRUD-y stuff, so if you don’t have fancy interactions, request specs are often good enough (and less flaky). But I hear you, Capybara selectors (especially with capybara_accessible_selectors) are so nice to use. So let’s use them in request specs!

It’s quite easy to get started. Add this to your RSpec configuration (somewhere in spec/support/capybara.rb):

module CapybaraPage
  def page
    Capybara.string(response.body)
  end
end

RSpec.configure do |config|
  config.include CapybaraPage, type: :request
end

What about within?, you might ask. Well, that depends on a Capybara::Session object, but we can get something similar by writing expectations with a block:

get users_path

expect(page).to have_table "Users" do |table|
  expect(table).to have_content user.name
  expect(table).to have_content user.email
end

And voilà! You now have requests specs that run fast* and have powerful expectations to assert the page content!

If that idea excites you, we’ve created a gem that implements that automatically for you: action_dispatch-testing-integration-capybara.