【问题标题】:after_create callback not working in test but works in consoleafter_create 回调在测试中不起作用,但在控制台中起作用
【发布时间】:2011-03-15 08:56:39
【问题描述】:

在 Rails 中进行测试一直是个谜,如果可能的话我会尽量避免,但我正在将一个生产应用程序放在一起,人们会为此付费,所以我真的需要测试。这个问题让我很生气,因为测试失败但是当我在控制台中执行相同的命令时(在测试和开发模式下)它工作正常。

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

缺席.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

我唯一的想法是,这与通过 Absence 模型上的回调更新 User 模型有关,但正如我所说,这在控制台中有效。

任何建议将不胜感激。

谢谢

罗宾

【问题讨论】:

    标签: ruby-on-rails unit-testing activerecord callback


    【解决方案1】:

    你的工厂用什么?

    如果你使用的是数据库支持的测试,那么你需要在测试中重新加载用户(因为用户实例没有更新,缺席的用户被更新并保存到数据库中),重新加载用户看起来像:

    assert_equal user.reload.holidays_booked_this_year, 5
    

    我也猜想缺席需要有一个用户,所以你应该使用 build 而不是 create 所以用户的外键是“创建”实例的一部分:

    user.absences.build
    

    首先猜测是,在控制台中,您正在对数据库中的真实用户进行操作,而测试是固定装置。你试过这个在测试中吗?:

    raise user.inspect
    

    查看输出并确定您实际使用的是哪个用户以及 holiday_booked_this_year 属性是什么。

    (你的测试块在描述之后也需要一个“do”)

    【讨论】:

    • 谢谢布兰登。我不小心省略了上面的“do”;它肯定存在于我的代码中。我会在上面尝试您的建议并报告。
    • 谢谢布兰登。调用了重新加载,现在测试通过了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    • 2017-06-29
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    相关资源
    最近更新 更多