Tim Harvey :: Blog

Icon

I help organizations who feel stuck

rSpec “Can’t find first {objectName}”

While cleaning up several rSpec tests for a Ruby on Rails app, I ran across an error that didn’t show up in Google. It didn’t make sense that my tests kept failing.

The solution was simple, but not obvious to a new rSpec user. The clean way to specify a validation is:

it { should validate_uniqueness_of( :title ) }

Unfortunately, I kept getting the error “Can’t find first Post” (where Post is the name of my object being tested. After some digging, it turns out that the shorthand notation assumes that you will have already added at least one Post to the database. It finds the first Post, then adds an identical one, expecting a failure.This would have been fine, but my “before” block didn’t have the usual

Post.create!( :title => 'Title' )

Instead, I had:

@valid_attributes = { :title => 'Title' }

So…you can either have your before block add at least one record, or skip the clean notation and do this:

it "should only accept unique Titles" do
  Post.create!(@valid_attributes)
  Post.new.should validate_uniqueness_of( :title )
end

That’s it!

Rev up your Pragmatic Programmer PDF books

As a Ruby developer who spend a considerable amount of time with Rails, I’m a huge fan of the Pragmatic Programmer books and own a ridiculous number of them. While I have read several cover to cover, I find them most useful as reference guides when I need help on a specific topic.

Google is always a good place to look, but I find that technical books offer a better look at a topic when I need a good overview and want to see how the solution fits into the tool set as a whole.

Software craftsmanship encourages excellence and that means keeping all your tools in top shape. In that vein, I constantly tweak my PDF books with Adobe Acrobat after each download to make sure I spend as little time navigating the book as possible. The screencast below shows the quick process I go through.

Rev up your Pragmatic Programmer PDF books from Tim Harvey on Vimeo.