开发者

after_create callback not working in test but works in console

Testing in Rails has always been something of a mystery that I avoid if possible but I'm putting a production application together that people will pay for so I really need to test. This problem is driving me mad because the test fails but when I perform the same commands in the console (in test and development mode) it works fine.

user_test.rb

test "should update holidays booked after create"
  user = users(:robin)
  assert_equal user.holidays_booked_this_year, 4 # this passes
  absence = user.absences.create(:from => "2011-12-02", :to => "2011-12-03", :category_id => 1, :employee_notes => "Secret") # this works
  assert_equal user.holidays_booked_this_year, 5 # fails
end

absence.rb

after_create :update_holidays_booked

def update_holidays_booked
  user = self.user
  user.holidays_booked_this_year += self.days_used # the days used attribute is calculated using a before_create callback on the absence
  user.save
end

My only thoughts ar开发者_JAVA技巧e that it's something to do with updating the User model through a callback on the Absence model but, as I say, this works in the console.

Any advice would be appreciated.

Thanks

Robin


What are you using for your factory?

If you are using a database backed test then you need to reload the user in the test (because the user instance is not updated, the absence's user is updated and saved to the database), reloading the user would look like:

assert_equal user.reload.holidays_booked_this_year, 5

I would also guess that an absence needs to have a user, so you should use build instead of create so the foreign key for user is part of the "created" instance:

user.absences.build

First guess would be that in the console you are operating on a real user in the database whereas the test is a fixture. Have you tried this is in test?:

raise user.inspect

Look at the output and determine which user you are actually working with and what the holidays_booked_this_year attributes is.

(your test block also needs a "do" after the description)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜