简体   繁体   English

如何在ruby的state_machine中存根所有条件方法以进行测试?

[英]How to stub all condition methods in ruby's state_machine for testing?

I am using state_machine with rails to handle state on some active record models and testing them with rspec and factory girl. 我正在使用带导轨的state_machine处理一些活动记录模型上的状态,并使用rspec和factory girl测试它们。 I also have a serialized array property called state_path that keeps track of the state history. 我还有一个名为state_path的序列化数组属性,用于跟踪状态历史记录。

class Project < ActiveRecord::Base
  serialize :state_path, Array

  def initialize(*)
    super
    state_path << state_name
  end

  state_machine :state, :initial => :draft do
    after_transition do |project, transition|
      project.state_path << transition.to_name
    end

    event :do_work do
      transition :draft => :complete, :if => :tps_has_cover_page?
    end

    state :draft do
      # ...
    end

    state :complete do
      # ...
    end
  end

  private
    def tps_has_cover_page?
      # ...
    end
end

Now, to test that the after_transition hook is properly populating the state_path property, I stub out the tps_has_cover_page? 现在,要测试after_transition挂钩是否正确填充了state_path属性,我对tps_has_cover_page?进行了存根tps_has_cover_page? transition condition method, because I don't care about that functionality in this test, and also it is integrated with other models (tps report model perhaps?) 转换条件方法,因为我在此测试中并不关心该功能,而且它已与其他模型集成(也许是tps报告模型?)

it "should store the state path" do
  allow_any_instance_of(Project).to receive(:tps_has_cover_page?).and_return(true)

  project = create(:project)
  project.do_work

  expect(project.state_path).to eq([:draft, :complete])
end

However, the transition condition method name could change, or more conditions could be added, which I'm not really concerned with in this test (obviously, since I'm stubbing it). 但是,过渡条件方法的名称可能会更改,或者可以添加更多条件,这在本测试中我并没有真正关注(显然,因为我正在对它进行存根)。

Question: is there a way to dynamically collect all of the transition condition methods on a state machine? 问题:有没有一种方法可以动态收集状态机上的所有转换条件方法? To then be able to build a macro that stubs out all of the condition methods? 为了能够建立一个存根所有条件方法的宏?

尝试:

transition_conditions = state_machine.events.map(&:branches).flatten.flat_map(&:if_condition)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM