我在使用Factory Girl
測試StateMachine
s時遇到了一些問題。它看起來像Factory Girl初始化對象的方式。使用FactoryGirl和StateMachine測試動態初始狀態
我是否錯過了一些東西,或者它不是那麼容易?
class Car < ActiveRecord::Base
attr_accessor :stolen # This would be an ActiveRecord attribute
state_machine :initial => lambda { |object| object.stolen ? :moving : :parked } do
state :parked, :moving
end
end
Factory.define :car do |f|
end
因此,初始狀態取決於在初始化過程中是否設置了stolen
屬性。這似乎很好地工作,因爲ActiveRecord的屬性集作爲其初始化的一部分:
Car.new(:stolen => true)
## Broadly equivalent to
car = Car.new do |c|
c.attributes = {:stolen => true}
end
car.initialize_state # StateMachine calls this at the end of the main initializer
assert_equal car.state, 'moving'
但是因爲工廠女孩前單獨設置它的覆蓋(見factory_girl/proxy/build.rb)初始化對象,這意味着流動更像是:
Factory(:car, :stolen => true)
## Broadly equivalent to
car = Car.new
car.initialize_state # StateMachine calls this at the end of the main initializer
car.stolen = true
assert_equal car.state, 'moving' # Fails, because the car wasn't 'stolen' when the state was initialized