RSpec Scaffolding View Spec Errors in Rails 3.1

Rails 3.1 was released yesterday and I decided to update a large project I was working on to it.  I have that kind of leisurely time table to be able to do that.  I’m kidding, I’m already getting asked when it’ll be done but since 3.1 came out I wanted to take a day and see what I was up against for future projects.

I’ve really taken to the whole testing idea.  I love rspec and have been using it on my projects.  I don’t normally use scaffolding in my apps but I thought since it was a new version of rails that I’d check out what was generated with the scaffold to see if I needed to update my standard way of doing things.  I’m still fairly new to rails so it’s nice to see an “official” way of doing things.

After running four or five scaffold generations I decided to fire up rspec and see what happened.  That’s when I got this ugly failure popping up:

Failure/Error: assert_select "tr>td", :text => 1.to_s, :count => 2
MiniTest::Assertion:
Expected exactly 2 elements matching "tr > td", found 8.

This was in my index.html.erb file and was odd.  Digging into the spec file I noticed that I have four integer fields.  It’s trying to test these four integer fields by using 1.to_s and complaining because it’s seeing 8 instead of 2.  Well, it’s going to see 8 because it stubs two records both containing 4 integer fields all with the same integer.

So my solution to the problem was to edit the spec file and change the integer fields from 1 to sequential numbers.  So 1,2,3 and 4 in my case.  I did this both in the stub_model sections and below in the “renders a list of <model>” block.  Once those were updated the tests all pass and I can move on knowing it’s actually working.