rspec: error on attribute (which exists) not found

2019-04-02 03:05发布

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?

1条回答
相关推荐>>
2楼-- · 2019-04-02 03:27

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
查看更多
登录 后发表回答