View Testing

Learn about the assert_select method and view testing in Rails.

View testing involves checking the presence or absence of certain key HTML elements used in your views and the contents of these HTML elements.

The assertions made for view testing are done through assert_select.

The tests for views reside in test/controllers/ and are written in the file for the associated controller.

The tests for the app/views/links will be written in the test/controllers/links_controller_test.rb file.

The assert_select method

Before you can process with writing tests for your views, you will have to learn a new assertion: assert_select.

The assert_select method provides you with ways to query HTML elements in your tests.

assert_select 'title'

The assertion above will look for the <title> HTML element in view.

The method selects elements and allows you to perform one or more equality tests, such as:

  • true: Assertion is true if at least one element is selected/found. true is the default second argument.

    •  assert_select 'title', true
    • If the <title> elements exists on the view, this assertion will be true.
  • false: Assertion is true if no matching elements are found.

    • assert_select 'title', false
    • If a <title> element is found, this assertion will be false. It expects for there to be no <title> elements on the current view.
  • integer: Assertion is true if the number of elements found are equal to the integer value.

    • assert_select 'h2', 4
    • This assertion will be true if exactly 4 <h2> elements are found on the view.
  • string/regex: Assertion is true if at least one element has the text provided as the string/regex.

    • assert_select 'title', "RailsApp"
    • This assertion will be true if the text in the <title> element is RailsApp.

assert_select can also be used in a nested manner. In this case, the inner assert_select receives all the elements selected by the outer assert_select as an array. This array can be iterated over.

Writing view tests

You will be writing a few simple tests for the views associated with your Links controller.

Tests for index view

Let’s write a test to check whether your index view contains an <h1> tag and whether this <h1> tag has the content Links.

In test/controllers/links_controller_test.rb you will create a new test:

Get hands-on with 1200+ tech skills courses.