我正在使用带有rails的state_machine
来处理某些活动记录模型上的状态,并使用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
但是,转换条件方法名称可能会更改,或者可能会添加更多条件,我在此测试中并不关心(显然,因为我正在对其进行存根)。
问题:有没有办法动态收集状态机上的所有转换条件方法?那么能够构建一个存根所有条件方法的宏吗?
答案 0 :(得分:1)
尝试:
transition_conditions = state_machine.events.map(&:branches).flatten.flat_map(&:if_condition)