【问题标题】:How to stub all condition methods in ruby's state_machine for testing?如何在 ruby​​ 的 state_machine 中存根所有条件方法进行测试?
【发布时间】:2014-03-02 11:45:31
【问题描述】:

我正在使用 state_machine 和 rails 来处理一些活动记录模型的状态,并使用 rspec 和 factory girl 对其进行测试。我还有一个名为 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

现在,为了测试after_transition 钩子是否正确填充state_path 属性,我将tps_has_cover_page? 转换条件方法存根,因为我不关心这个测试中的功能,而且它也是与其他模型集成(可能是 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

但是,转换条件方法的名称可能会更改,或者可能会添加更多条件,我在此测试中并不真正关心(显然,因为我正在对它进行存根)。

问题:有没有办法动态收集状态机上的所有转换条件方法?然后能够构建一个存根所有条件方法的宏?

【问题讨论】:

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


    【解决方案1】:

    试试:

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

    【讨论】:

    • 我必须先展平树枝,然后才能制作最终的平面地图,因为树枝本身被包裹在数组中。 Project.state_machine.events.map(&amp;:branches).flatten.flat_map(&amp;:if_condition) 否则效果很好!感谢您的回答,您可以确认展平吗?如果是,我会接受答案。
    • 运行 state_machine 1.2.0 btw
    • 如果你也需要这些,分支内也有:unless_conditions:unless_conditions
    • @ianstarz 如果这个答案对你有帮助 - 投票。如果它解决了您的问题 - 接受它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-10
    • 1970-01-01
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    • 2011-03-14
    相关资源
    最近更新 更多