Over a million developers have joined DZone.

Rendering views in rspec controller tests

DZone 's Guide to

Rendering views in rspec controller tests

· ·
Free Resource

Normally I love the fact that rspec doesn’t render views when testing controllers, but I have one instance where this was needed. I needed to render some coffeescript through erb based on a controller action. I called the erb template using render_string, then passed the returned string to the coffeescript compiler. Not really the most elegant solution, but it does work well.

My real problem came when I needed to test it. Using cucumber didn’t make much sense to me so I wanted to do it through rspec. I already had the controller written and manually tested so test first wasn’t an option. I broke my coffeescript on purpose just to prove that the test would fail, had my spec looking for an response code of 200 since I knew if the coffeescript compile failed, it would return a 500.

I ran my spec and to my surprise it passed.

It failed everywhere else in every manual test I did, even if I loaded the rails test environment. Only the rspec test passed. Previous to this, I had never used rspec to test anything related to rendering views from a controller so it didn’t occur to me that rspec wouldn’t process the view template at all. 

So to get it to work, I found an option that will allow your controller specs to render views. It’s an edge case so it wasn’t easy to find, but it’s pretty simple to do.

All you need to do is call integrate_views after describe YourController and it will also render the view.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}