Rob*_*her 4 activerecord unit-testing ruby-on-rails callback
Rails 中的测试一直是个谜,如果可能的话我会避免这样做,但我正在将一个生产应用程序放在一起,人们会为此付费,所以我确实需要测试。这个问题让我很生气,因为测试失败了,但是当我在控制台中执行相同的命令(在测试和开发模式下)时,它工作正常。
用户测试.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
Run Code Online (Sandbox Code Playgroud)
缺席.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
Run Code Online (Sandbox Code Playgroud)
我唯一的想法是,这与通过缺席模型上的回调更新用户模型有关,但正如我所说,这在控制台中有效。
任何意见,将不胜感激。
谢谢
罗宾
你的工厂用什么?
如果您使用的是数据库支持的测试,那么您需要在测试中重新加载用户(因为用户实例未更新,缺勤的用户会更新并保存到数据库中),重新加载用户将如下所示:
assert_equal user.reload.holidays_booked_this_year, 5
Run Code Online (Sandbox Code Playgroud)
我还猜测缺勤需要有一个用户,因此您应该使用 build 而不是 create,以便用户的外键是“创建”实例的一部分:
user.absences.build
Run Code Online (Sandbox Code Playgroud)
第一个猜测是,在控制台中,您正在数据库中的真实用户上进行操作,而测试是固定装置。您是否尝试过这个正在测试中?:
raise user.inspect
Run Code Online (Sandbox Code Playgroud)
查看输出并确定您实际使用的用户以及holidays_booked_this_year 属性是什么。
(您的测试块在描述后还需要一个“do”)
| 归档时间: |
|
| 查看次数: |
3088 次 |
| 最近记录: |