Validating Views with Capybara Queries

Jon Yurek - Mar 29 '22 - - Dev Community

When you write a system test (or, as we prefer, a system spec) with Ruby on Rails, you're exercising the whole stack from the point of view of the user. So, naturally, you have to do things like make sure that certain elements are on the page and work as you expect when you click on then, type in them, and drag them around. Capybara works exceedingly well for this, giving you a lovely API for querying HTML.

But system specs are heavy. They need everything spun up. They need a browser. They're faster than a person clicking around, but they need to do things like wait for pages to load, animations to finish, and Promises to resolve. If you can, it's much cleaner to test whether or not you have data in your HTML by using a view spec. You only have to use exactly what the template needs, and stubbing or mocking to get ensure coverage is far less onerous and invasive. Since a view spec only has to worry about rendering the view (and returning a String), it doesn't have to load a whole browser.

Even in the Relish documentation linked above, we see that a lot of view specs involve straight text matching. You could try Rails' assert_select, which makes more structured queries, but an even easier solution exists.

Capybara.string is a very straight forward method that turns a string into a queryable document. Working with it involves little overhead, especially if you have Capybara installed already (and even if you don't).

it "renders the account link when signed in" do
  user = FactoryBot.build_stubbed(:user)
  assign(:current_user, user)

  render partial: "layouts/nav"

  doc = Capybara.string(rendered)
  expect(doc).to have_css("nav a[href='/users/#{user.id}']", text: "Account")
end

it "does not render the account link when signed out" do
  assign(:current_user, nil)

  render partial: "layouts/nav"

  doc = Capybara.string(rendered)
  expect(doc).to have_no_css("nav a", text: "Account")
end
Enter fullscreen mode Exit fullscreen mode

You get access to all the Capybara matchers, and, with RSpec, you get the nice inflections that make your specs very readable. And since render already puts its result into rendered, it's very easy to make that into a usable document with Capybara.string.

Learn more about how The Gnar builds Ruby on Rails applications.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .