开发者

rspec: error on attribute (which exists) not found

开发者 https://www.devze.com 2023-02-06 13:09 出处:网络
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:

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 somebo开发者_StackOverflowdy explain that?


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
0

精彩评论

暂无评论...
验证码 换一张
取 消