1

Imagine you have two templates:

# app/views/users/foo.haml.html
%p ...

# app/views/users/bar.haml.html
%p ...

And a controller that renders these:

MyApp.controllers :users do
  get '/herp' do
    render 'users/foo'
  end
  get '/derp' do
    render 'users/bar'
  end
end

What's the best way to write an RSpec test that asserts that a particular view was rendered by a controller?

Ideally, is there a way to have the test check only that the view would have been rendered, without actually rendering it?

John Feminella
  • 303,634
  • 46
  • 339
  • 357

1 Answers1

0

You could use Rack::Test to check the rendering of the page:

RSpec.configure do |config|
  config.include Rack::Test::Methods
  # other stuff too…
end


describe "Getting the user's page", :type => :request do
  let(:username) { "herp" }
  before do
    get "/users/#{username}"
  end
  subject{ last_response }
  its(:status) { should == 200 }
  its(:body) { should include "Something that was on the template" }
end

Once that's working you could generalise it to generate different usernames to run the spec against and suchlike.

To check the page would have been rendered without rendering it, perhaps you could double the render method?

ian
  • 12,003
  • 9
  • 51
  • 107
  • I don't want to make the test be a string match, because that's too brittle: If the view changes, the test should still work, since nothing in the controller was altered. I guess it's possible to double on `render`, I hadn't thought of that. That's probably the best approach. – John Feminella Apr 08 '14 at 18:05
  • @JohnFeminella Well, the rendered output is a string, after all :) You may also want to run some kind of validity check on the template too, because without actually running it you won't know if a problem with the template would've caused an error in the renderer. – ian Apr 08 '14 at 18:30
  • I agree that it's also a string match, but this string doesn't change when I edit the contents of the view. :) – John Feminella Apr 08 '14 at 19:16
  • @JohnFeminella My view is that sometimes a test needs to be tied to something specific, even if it introduces a brittleness, because that's just the way it is. I quite regularly introduce these kind of specs, you have to pay the piper somewhere :) – ian Apr 08 '14 at 20:19