rspec:未找到属性(存在)错误
我在指定模型验证时遇到一些问题,该模型充当状态机(gem state_machine 0.9.4)。通过 stat_machine,我定义了对交付状态下的自行车的验证:
state :delivered do
validates_presence_of :shipping_number
end
在我的规格中,这是正确的:
it "may not transit to :delivered without a shipping number " do
@bike.state = 'delivered'
@bike.shipping_number = nil
@bike.save
@bike.should have(1).error_on(:shipping_number)
end
但是当像这样指定时:
it "may not transit to :delivered without a shipping number " do
@bike.shipping_number = nil
@bike.deliver
@bike.should have(1).error_on(:shipping_number)
end
我得到:
expected 1 error on :shipping_number, got 0
即使
it "may not transit to :delivered without a shipping number " do
@bike.shipping_number = nil
@bike.deliver
raise @bike.errors.inspect
end
向我展示:
Failure/Error: raise @bike.errors.inspect
#<OrderedHash {:shipping_number=>["can't be blank"]}>
有人可以解释一下吗?
I've got some problems specing a validation of my model, which acts as a state machine (gem state_machine 0.9.4). Via the stat_machine, I defined a validation for bikes in the state delivered:
state :delivered do
validates_presence_of :shipping_number
end
in my specs this works right:
it "may not transit to :delivered without a shipping number " do
@bike.state = 'delivered'
@bike.shipping_number = nil
@bike.save
@bike.should have(1).error_on(:shipping_number)
end
but when specing like this:
it "may not transit to :delivered without a shipping number " do
@bike.shipping_number = nil
@bike.deliver
@bike.should have(1).error_on(:shipping_number)
end
I get:
expected 1 error on :shipping_number, got 0
even though
it "may not transit to :delivered without a shipping number " do
@bike.shipping_number = nil
@bike.deliver
raise @bike.errors.inspect
end
shows me:
Failure/Error: raise @bike.errors.inspect
#<OrderedHash {:shipping_number=>["can't be blank"]}>
can somebody explain that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
检查这里的链接,它解释了这个问题:
http: //web.archive.org/web/20130202082209/http://agaskar.com/post/1627270986/fun-state-machine-rspec-gotcha
底线:失败的状态转换会导致回滚到之前的状态,现在 validates_presence_of 与以下错误检查无关。
虽然可能有一种更惯用的方法来做到这一点,但我在规范中做了类似的事情:
Check this link here, it explains the issue:
http://web.archive.org/web/20130202082209/http://agaskar.com/post/1627270986/fun-state-machine-rspec-gotcha
Bottom line: failed state transition causes a rollback to the previous state, and now the validates_presence_of is not relevant for the following check of errors.
Though there's probably a more idiomatic way to do it, I did something like this in the spec: