Ruby on rails 在产品具有一个状态且状态机作用于关联的情况下,如何为rspec测试添加种子数据
我有两种型号Ruby on rails 在产品具有一个状态且状态机作用于关联的情况下,如何为rspec测试添加种子数据,ruby-on-rails,ruby,rspec,state-machine,Ruby On Rails,Ruby,Rspec,State Machine,我有两种型号产品和状态 在产品模型中,我有 class Product < ActiveRecord::Base attr_accessible :image_url, :name, :status_id belongs_to :status state_machine :status_id, :initial => :dead do event :activate do transition all => :active en
产品
和状态
在产品模型中,我有
class Product < ActiveRecord::Base
attr_accessible :image_url, :name, :status_id
belongs_to :status
state_machine :status_id, :initial => :dead do
event :activate do
transition all => :active
end
event :de_activate do
transition all => :dead
end
event :set_out_of_stock do
transition all => :out_of_stock
end
state :active, :value => Status.where(:code=>"ACTIVE").first.id
state :dead, :value => Status.where(:code=>"DEAD").first.id
state :out_of_stock, :value => Status.where(:code=>"OUT_OF_STOCK").first.id
end
end
类产品:dead do
事件:激活do
全部转换=>:活动
结束
事件:取消激活do
全部转换=>:死
结束
事件:设置库存量
全部转换=>:缺货
结束
state:active,:value=>Status.where(:code=>“active”).first.id
state:dead,:value=>Status.where(:code=>“dead”).first.id
状态:缺货,:value=>Status.where(:code=>“缺货”).first.id
结束
结束
在运行rspec时,它会首先尝试加载产品模型,并给出错误提示,nil.id
为4等等,因为状态未填充
如何在加载模型之前预加载状态数据?我怀疑这是最佳解决方案,但您可以将状态机初始化(即
状态机
方法调用)放置在产品
的类方法中,并在填充状态
后显式调用该方法。我已经测试过了,它似乎工作得很好