rspec:未找到属性(存在)错误 [英] rspec: error on attribute (which exists) not found

查看:48
本文介绍了rspec:未找到属性(存在)错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在指定模型验证时遇到了一些问题,该模型充当状态机 (gem state_machine 0.9.4).通过 stat_machine,我定义了自行车在交付状态下的验证:

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

但是当这样指定时:

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"]}>

有人能解释一下吗?

推荐答案

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

Check this link here, it explains the issue: http://web.archive.org/web/20130202082209/http://agaskar.com/post/1627270986/fun-state-machine-rspec-gotcha

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

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

这篇关于rspec:未找到属性(存在)错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆