ruby-on-rails - Product has_one状态和状态机作用于association的场景下如何为rspec测试添加种子数据

标签 ruby-on-rails ruby rspec state-machine

我有两个模型 ProductStatus

在产品模型中,我有

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

在运行 rspec 时,它首先尝试加载 Product 模型并给出错误提示 nil.id 是 4 等等....因为状态未填充。

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

最佳答案

我怀疑这是最佳解决方案,但您可以将状态机初始化(即 state_machine 方法调用)放在 Product 的类方法中并调用该方法在您填充 Status 之后明确。我已经对此进行了测试,它似乎工作正常。

关于ruby-on-rails - Product has_one状态和状态机作用于association的场景下如何为rspec测试添加种子数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18435324/

相关文章:

ruby-on-rails - Ruby 中的 "%"和 "/"符号差异

javascript - Rails - 时间轴 javascript 的路由问题

ruby-on-rails - 将操作关联到 Rails 中 form.select 的 on_change?

ruby - 使用键的值对散列进行排序

ruby-on-rails - Ruby on Rails - 在任何源中都找不到 xpath-2.0.0

ruby-on-rails-3 - Rspec、CanCan 和 Devise

ruby-on-rails - Rails查询相关表列值

ruby-on-rails - ruby roo gem : comparison of Fixnum with nil failed (ArgumentError)

ruby - 这个 Ruby 应用程序如何知道选择句子的中间三分之一?

ruby-on-rails - 在 rails 中使用 RSpec 和 Capybara 时未定义的方法 `visit'