Rails 测试跳过自定义验证或自定义验证不起作用?
Rails tests skipping custom validations or custom validation not working?
我有一个带有布尔属性 :fee
的模型 Subscription
,在创建 Subscription
.
后不应对其进行修改
我添加了这样的自定义验证:
validate :fee_not_changed
def fee_not_changed
return unless created_at != updated_at && fee_changed?
errors.add :fee, :changed, message: "cannot be changed"
end
我们的 API 不允许我们更新 :fee
(返回错误)但我可以在测试中更新属性,尽管自定义验证如下:
test "fee cant be edited after creation" do
subscription = subscriptions(:with_fee)
subscription.update!(fee: false)
assert_not subscription.saved_change_to_fee?
end
Expected true to be nil or false
另外,如果我在断言前加上 byebug
,我可以看到它有效地更新了跳过自定义验证的属性。
有什么问题吗?感谢您提供的任何帮助。
我认为这是一个缓存问题。
您可以尝试使用 .reload
重新加载订阅吗?
assert_not subscription.reload.saved_change_to_fee?
我有一个带有布尔属性 :fee
的模型 Subscription
,在创建 Subscription
.
我添加了这样的自定义验证:
validate :fee_not_changed
def fee_not_changed
return unless created_at != updated_at && fee_changed?
errors.add :fee, :changed, message: "cannot be changed"
end
我们的 API 不允许我们更新 :fee
(返回错误)但我可以在测试中更新属性,尽管自定义验证如下:
test "fee cant be edited after creation" do
subscription = subscriptions(:with_fee)
subscription.update!(fee: false)
assert_not subscription.saved_change_to_fee?
end
Expected true to be nil or false
另外,如果我在断言前加上 byebug
,我可以看到它有效地更新了跳过自定义验证的属性。
有什么问题吗?感谢您提供的任何帮助。
我认为这是一个缓存问题。
您可以尝试使用 .reload
重新加载订阅吗?
assert_not subscription.reload.saved_change_to_fee?