Multiplay Labs

tech hits and tips from Multiplay

Archive for the ‘shoulda’ tag

Shoulda woulda gotcha: setup doesn’t run when you think it runs

without comments

Lots of hair tearing over the last few hours due to a totally unexpected gotcha. Take the following code from a shoulda functional test:

context "Logging in as an inactive user" do
	setup do
		@user = Factory(:inactive_user)
		post :create, :login => "user@example.com", :password => "monkee"
	end
 
	should_redirect_to "users_activate_url(#{@user.id})"
end

On first glance, you’d think this would work right? Wrong. The setup isn’t called until after our should macro is evaluated, and so #{@user.id} fails with a nice WhinyNil error.

This would ideally be worked around by a block deferring the execution a-la factory_girl deferred blocks. I’ll have a think about how best to accomplish this and submit it to the Thoughtbot guys. In the meantime, the unfortunate workaround is to use an instance variable from your controller, like so:

should_redirect_to "users_activate_url(@user.id)"

Written by Boffbowsh

December 2nd, 2008 at 10:31 am

Posted in Code,Hackery

Tagged with , ,