Header_image
Jeremy Walker

Software Developer & Social Entrepreneur

Testing views with Rails 3, Rspec 2 and Webrat

I just lost an hour of my life on this issue, so hopefully I'll save someone else the waste!

My code:

require 'spec_helper'
describe ExamsController do
  it "should present the user with the new exam form" do
    get :index
    response.should have_selector('form#new_practice_exam_form')
  end
end

The output:

Failure/Error: response.should have_selector("")
expected following output to contain a tag:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">

Firstly, ignore the weird form tag it suggests it's looking for - this is a red herring. Webrat just outputs error messages badly.

The actual issue is simply that the HTML is not being rendered. By default, the views are not rendered in controller tests. One line of code fixes this:

require 'spec_helper'
 
describe ExamsController do
  render_views
  it "should present the user with the new exam form" do
    get :index
    response.should have_selector('form#new_practice_exam_form')
  end
end

Hope that helps someone!!

Update:As Snuggs points out in his comment below, if you find yourself testing view code in the controller, you're probably doing something wrong. View tests and integration (or request) tests are the correct place for this.

Share This Post

Comments

64436c814e3b8422fc25c0112760168c

Snuggles

Or you could just do view specs
- specs
- views
- your_view.html.erb_spec.rb

By default all view specs have a
:type => :request
option. You can set your describe type to be the same to get this functionality but this is usually a sign you are testing in the wrong area of your specs. Yes view tests aren't en vogue but at the end of the day you need to know if that form is on the page.

- Regards

955103d80e386882143a78875fb727bf

Jeremy Walker

Hi Snuggs,

Thanks for your comment. I actually subsequently moved this code into a view test just like you suggested. I also have a request test that checks this in a slightly different way.

I've updated the post to note your comment. Thanks!

Post a Comment

I'd love to hear your thoughts :)