[rspec-users] test for "lambda {...}.should change(x, y).by(z)" failing.. ?

Patrick J. Collins patrick at collinatorstudios.com
Wed Nov 23 16:33:42 EST 2011

I wrote a test that looked like this:

	it "increases the user's reputation" do
		lambda { @comment.update_attribute(:helpful, true) }.should change(@seller.reload, :reputation_score).by(Event.reputation_change_for(:mark_helpful))

And I am getting this error:
  1) Comment comments on posts marking a comment as helpful increases the user's reputation
     Failure/Error: lambda { @comment.update_attribute(:helpful, true) }.should change(@seller.reload, :reputation_score).by(Event.reputation_change_for(:mark_helpful))
       reputation_score should have been changed by 3, but was changed by 0


The way the actual code works is, I have a comment observer that does:

	def after_update(comment)
		Event.create_for_user(comment.user, :mark_helpful)

And event.rb does something like:

	def create_for_user(user, event_type)
		create!(:user => user, :reputation_change => Event::SCORES[event_type])

The user model has an before_save callback which does:

	def sum_points
		self.reputation_score = events.sum(:reputation_change)
		self.points = events.sum(:points_change)


Anyway, so this test fails, and I am not sure why...  If I write it in a
slightly less-cool way:

	it "increases the user's reputation" do
		@seller.reputation_score.should == 0
		@comment.update_attribute(:helpful, true)
		@seller.reload.reputation_score.should == Event.reputation_change_for(:mark_helpful)

Then it passes...  If I throw in a debugger statement in there and manually
call the code, the reputation_score does indeed increase......  So I am
confused why the lambda {}.change thing isn't working?


Patrick J. Collins

More information about the rspec-users mailing list