Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在产品具有一个状态且状态机作用于关联的情况下,如何为rspec测试添加种子数据_Ruby On Rails_Ruby_Rspec_State Machine - Fatal编程技术网

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等等,因为状态未填充


如何在加载模型之前预加载状态数据?

我怀疑这是最佳解决方案,但您可以将状态机初始化(即
状态机
方法调用)放置在
产品
的类方法中,并在填充
状态
后显式调用该方法。我已经测试过了,它似乎工作得很好