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 them, 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
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.
What does Capybara.string return, and what can it not do?#
Capybara.string returns a Capybara::Node::Simple, a node with Capybara's finders and matchers but no actions. It cannot click or type, and it needs no session, application or driver, according to the Capybara 3.40.0 source. This post says the method "turns a string into a queryable document", and the table below shows what that document can answer and what it leaves out.
Three terms come up in that source. A finder looks up elements in the document and returns them. A matcher checks one fact about the document, and the has_ methods answer true or false. An action changes a page, such as a click. Capybara's class documentation names each group by its module: Finders, Matchers and Actions. It calls the Simple node a simpler version of Capybara::Node::Base.
| Part of the node | What the Capybara 3.40.0 source says | Methods named |
|---|---|---|
| Finders | The class documentation says the node includes Finders. A finder called find raises Capybara:: | find, all, first |
| Matchers | The class documentation says the node includes Matchers. Each has_ method checks a fact and returns true or false. | has_ |
| Document matchers | The source describes has_title? as "Checks if the page has the given title." | has_ |
| Actions | The class documentation says the node does not include Actions. | None |
| Reading values | The node returns the text of an element, an attribute, the tag name, the value of a form element and the document title. | text, [], tag_ |
| Visibility | The source says the check "Does not support CSS, so the result may be inaccurate." | visible? |
| Waiting | A comment inside synchronize reads "simple nodes don't need to wait." | synchronize |
Capybara's README shows these pieces in a view spec. A view spec is an RSpec example that renders a Rails view template and checks the output. The README spec assigns one record titled Buy milk and calls render. It then expects rendered to have the CSS selector header h1 with the text Buy milk. The README says Capybara matchers are also supported in view specs.
Two lines in the source explain why that works. Requiring capybara/rspec includes Capybara::RSpecMatchers in specs of type :view. Then the matcher wrapper calls to_capybara_node on the value you give it when the value responds to that method. It uses the result when the result responds to has_selector?. Otherwise it calls Capybara.string on the result converted to a string.
A matcher that receives rendered therefore builds the same kind of document for you. Calling Capybara.string yourself gives you a node you can also call find on.
The Capybara.string documentation says the string should contain an HTML document or fragment. It says you can query that string the same way you would query the current document in a Capybara session. Its first example builds a node from a link, calls first on it, reads the href with [] and reads the text with text. Its second example calls find on an element with the id projects and reads its text, which is Projects.
A Capybara::Node::Simple includes three modules: Finders, Matchers and DocumentMatchers. The Capybara.string documentation says the node exposes all three. DocumentMatchers add has_title? and has_no_title?. Each takes a string or a regexp and an exact option, according to the document matchers source.
Which Capybara matchers and options fit a view spec?#
The Capybara 3.40.0 matchers that fit rendered HTML include has_css?, has_link?, has_button?, has_field?, has_table? and has_text?. Each has a has_no_ form that checks the opposite, and the RSpec versions are written have_css, have_no_css and so on. This post says "You get access to all the Capybara matchers", and the table lists what each one takes.
Most of these matchers take an optional locator, and has_text? takes the expected text instead. A locator is the text, id, label or selector that tells the matcher which element to look for. The options in the last column come from the matchers source and the finders source.
| Matcher | What it checks | Options the source names |
|---|---|---|
| have_ | Elements that match a CSS selector. | text, visible, count, minimum, maximum, between |
| have_ | A link found by its text or id. | href |
| have_ | A button found by its text, value or id. | id, name, title, value, disabled |
| have_ | A form field found by its label, name or id. | with, type |
| have_ | A table found by its id or caption. | rows, with_ |
| have_ | The text content, ignoring any HTML tags. | count, minimum, maximum, between, exact, normalize_ |
The button options in that table come from the list the finders source gives for find_button. For the rows, with_rows, cols and with_cols options of have_table, the source says the visibility of td elements is not considered. Capybara also lists have_content as an alias of have_text, and have_no_content as an alias of have_no_text.
Counts have their own options. The matchers source says has_selector? checks that an expression occurs at least once. Pass count for an exact number of matches. Pass minimum for at least that many, maximum for at most that many, or between for a range. The source gives has_selector? with count 4 as a check for exactly four matches. It gives has_text? with between 2..4 as a check that the text occurs from two to four times.
The matchers source also says has_selector? accepts the options that all accepts, such as text and visible. It says the same of has_css?. A count can therefore sit beside a text filter in one call. The source's own example calls has_selector? with li, the text Horse and visible set to true. That checks for visible list items that contain Horse.
The text option and the visible option filter matches. The finders source says text finds only elements which contain this text or match this regexp. It says visible takes true, false, :all, :hidden or :visible. The values true and :visible find only visible elements. The values false and :all find visible and invisible elements. The value :hidden finds only invisible elements.
On a Capybara.string document, the visible check has the limit listed in the first table: the source says visible? does not support CSS, so the result may be inaccurate.
To check that something is absent, use the have_no_ form. The RSpec matchers source defines a have_no_ form for many matchers, including have_no_css and have_no_text. The README says that for Capybara's RSpec matchers, not_to have_xpath and to have_no_xpath are functionally equivalent. This post's own code uses have_no_css.
What can a view spec set up before you query the HTML?#
A view spec tests the content of a view template without invoking a specific controller. It sets instance variables with assign, renders with render and reads the output from rendered, according to the rspec-rails 8.0 documentation. This post says "You only have to use exactly what the template needs", and the table lists the setup calls the documentation shows for that.
Rails and RSpec use six terms in those setup calls. An instance variable is a variable whose name starts with @, such as @widget. The rspec-rails docs say the assign method sets instance variables in the view. A local is a variable passed into one template. The Action View guide says each key in the locals option is available as a partial-local variable. A partial is a template file whose name starts with an underscore. The Layouts and Rendering guide says that underscore distinguishes partials from regular views. A layout is a template that wraps another. The Action View guide says the final HTML combines the ERB file, a layout template that wraps it and the partials it references. A helper is a method the view can call. The Action View guide says Rails provides many helper methods to use with Action View, such as methods for formatting dates, strings and numbers. A stub replaces a method's answer. The rspec-rails docs stub the helper admin? so that it returns true.
| What the template needs | What the rspec-rails docs show | What the docs say, in short |
|---|---|---|
| An instance variable | assign with the name :widget and a new Widget | "sets @widget = Widget.new in the view template" |
| The described view | render with no arguments | "View specs render the described view file" |
| A different template | render with the template option "widgets/widget" | Renders that template. |
| A layout around it | render with the template option and the layout option "layouts/inventory" | Renders the template inside that layout. |
| Locals for a template | render with the locals option | Gives the template a local variable named widget. |
| A partial and its locals | render with the partial option "widgets/widget" and the locals option | Renders the partial with its locals. |
| An implicit partial | render "widgets/widget" with widget given directly | Renders the partial with a local named widget. |
| Plain text | render with the plain option | Renders the given text. |
| A helper's answer | allow on view with receive and and_ | Stubs a helper method such as admin? |
The documentation marks view specs with type: :view. If you set config.infer_spec_type_from_file_location!, a file in spec/views gets that type. The described view comes from the string after describe. The documentation shows describe "widgets/index" for the file app/views/widgets/index.html.erb. It also shows describe strings that include the format and handler, such as "widgets/widget.xml.erb", which renders the XML template.
Setup can sit in a before block. The documentation shows a nested context whose before block calls assign with a list of two widgets. The example in that context then calls render and checks rendered.
Capybara matchers reach view specs through capybara/rspec. The capybara/rspec source includes Capybara::RSpecMatchers in specs of type :view. A spec of that type can then pass rendered to have_css, have_link or have_text.
Learn more about how The Gnar builds Ruby on Rails applications.


