【发布时间】: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