Today we’ll be covering view specs. I’ve found that this excerpt from the book Rails Test Prescriptions describes the goals of writing view specs quite well.
Create a view test when you want to do one of the following things:
Validate that the view layer runs without error.
Validate that the data gathered by the controller is expressed as expected in the view.
Validate security-based output.
View layer should run without error
We can assert in our tests that the correct view file or partial is being rendered in its proper place. For this, we can write a spec something like this:
Controller gathered data is expressed in the view as expected
Here, we’ll want to test that any view logic dependent on the presence or absence of particular data works properly.
We’ve just seen an example of our
index method, now we want to test that our view file
views/users/index.html.erb file can receive a list of all users. We can create a spec for this like so:
We use Factory Girl to create our
user object, and assign an email address to this object while we’re at it. The
render method in the next line, will call the path from the most outermost
describe block when no arguments are provided to it. In this case, our outermost
describe block is the view page. Lets see the entire
index.html.erb_spec.rb file for good measure:
Line 3 from the illustration above is our most outside
describe block, and its path is
users/index.html.erb and can be called with
We can also see the
context "when rendering the user template" block on line 4. I’m not sure that our test is in need of a
context mention at this stage, and I may or may not end up removing the
context block, depending on how the rest of the specs go.
I remember hearing in one of my AirPair’s that newbie developers have a tendency to overuse new tools, and this could easily be the case here. If so, feel free to comment and I’ll make the necessary adjustments.
Security Based Output
This means we can create specs for things such as a user being able to update their email, but not that of another users’. Here are a pair of specs for illustration:
Above we’ve added one spec to assert the presence of an expected
user.email and another spec to assert that we should not receive an email that does not match the
I’ll be having a couple mentor sessions this week that will help me better understand view testing. And I’ll write a follow up post on what I’ve learned.