rspec:未找到属性(存在)错误

发布于 2024-10-13 08:55:25 字数 1058 浏览 4 评论 0原文

我在指定模型验证时遇到一些问题,该模型充当状态机(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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

层林尽染 2024-10-20 08:55:25

检查这里的链接,它解释了这个问题:
http: //web.archive.org/web/20130202082209/http://agaskar.com/post/1627270986/fun-state-machine-rspec-gotcha

底线:失败的状态转换会导致回滚到之前的状态,现在 validates_presence_of 与以下错误检查无关。

虽然可能有一种更惯用的方法来做到这一点,但我在规范中做了类似的事情:

@bike.errors.include?(:shipping_number).should == true

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:

@bike.errors.include?(:shipping_number).should == true
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文