我有一个模型,我在其中实现了一个验证,以防止在设置初始值后进行更改。
它的工作原理如下:
模型/ deal.rb
validate :quantity_not_changeable
def quantity_not_changeable
if quantity_changed? && self.persisted?
errors.add(:quantity,"Change of quantity is not allowed. Delete and re-create the deal.")
end
end
这适用于我的应用。但是我试图用Rspec测试这个,而不是设法做到这一点。
我试过测试这个,但是测试失败了。
describe Deal do
let(:admin_user) { FactoryGirl.create(:admin_user) }
before(:each) do
@attr = {
title: "Neque porro quisquam est qui dolorem",
description: "lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum",
quantity: 10
}
end
describe "my test" do
it "fails if initial quantity is changed" do
msg_error = "Change of the initially defined qty is impossible"
hash = @attr.merge(quantity: 5)
deal = Deal.new(hash)
expect(deal).to have(1).errors_on(:quantity)
end
end
但是我得到了这个rspec错误:
Failure/Error: expect(deal).to have(1).errors_on(:quantity)
expected 1 errors on :quantity, got 0
如何使这项工作真正测试不可能改变数量?
修改
我现在明白为什么测试是假的,但不知道如何处理它。
如果我删除self.persisted?从下面的代码,我正在使用的测试通过。所以问题来自坚持?
def quantity_not_changeable
if quantity_changed?
errors.add(:quantity,"Change of quantity is not allowed. Delete and re-create the deal.")
end
end
但是我不想删除它,因为我实际上需要它:我只想在已经有值时阻止更改字段,所以我想忽略新记录。
答案 0 :(得分:1)
您应该编辑模型:
validate :quantity_not_changeable, on: :update
def quantity_not_changeable
if quantity_changed?
errors.add(:quantity,"Change of quantity is not allowed. Delete and re-create the deal.")
end
end
然后在声明中:
it "fails if initial quantity is changed" do
msg_error = "Change of the initially defined qty is impossible"
deal = Deal.create!(@attr)
deal.update(quantity: 5)
expect(deal).to have(1).errors_on(:quantity)
end
答案 1 :(得分:0)
您需要创建Deal
,以便persisted?
检查有效,然后更新您的quantity
属性,以便进行第二次检查{{1也会工作:
quantity_changed?