For almost two years now, I’ve been telling people I never write view specs for my Rails applications. They’re hard to write and harder to manage over time. I don’t even talk about them in Everyday Rails Testing with RSpec–as a general rule, I try to either test view-related matters in my feature specs, or better yet, extract the stuff that needs testing into more testable layers of my application.
So why did I write a view spec the other day?
Here’s the general idea:
In this case, the environment variables are loaded into Rails via dotenv. If a developer (or continuous integration tool) doesn’t have these variables set, the test will fail. It also served as a guide as I wrote the actual code to make it pass. All this in a spec that took about two minutes to write, and runs in an instant.
I’m still not advocating trying to cover every view with a view spec. All the same, they can serve a purpose and belong in your RSpec toolbox.
If you liked my series on practical advice for adding reliable tests to your Rails apps, check out the expanded ebook version. Lots of additional, exclusive content and a complete sample Rails application.
Ruby on Rails news and tips, and other ideas and surprises from Aaron at Everyday Rails. Delivered to your inbox on no particular set schedule.