更新
答案如下。 如果链接的站点消失,您可以使用 mocha 来存根初始状态并防止覆盖,如...
require 'mocha'
class OrderTest < ActiveSupport::TestCase
def setup
Order.any_instance.stubs(:set_initial_state)
@order = Factory(:order, :state => "other_state")
end
...
end
原始问题
我当前正在运行 Acts As State Machine Rails 插件(顺便说一句,它节省了大量时间)并有一些挑战与 Factory Girl 一起使用它(也很棒)。
我希望能够在使用工厂创建对象时设置对象状态。 提出这个问题的一般方法是“在使用工厂创建对象时如何调用类方法?”
class Transporter < ActiveRecord::Base
validates_presence_of :company_name, :on => :update
acts_as_state_machine :initial => :created, :column => 'status'
state :created
state :active
state :inactive, :after => :inactivate_transporter_activity
end
Factory.define :transporter do |f|
f.sequence(:company_name) {|n| "transporter_company#{n}"}
end
>> t=Factory(:transporter)
=> <Transporter ... status: "created">
>> t=Factory(:transporter, :status => 'active')
=> <Transporter ... status: "created"> #as expected, changes state back
>> t.activate!
=> true
>> t
=> <Transporter ... status: "active">
我随时可以调用 t.activate! 每个测试中的方法,但这将使我的测试变得脆弱。 我正在寻找一种在工厂创建级别运行此方法或在factory.rb 中设置它的方法。
谢谢...
Update
Answered below. In case the linked site disappears, you can use mocha to stub the initial state and prevent overwriting as in ...
require 'mocha'
class OrderTest < ActiveSupport::TestCase
def setup
Order.any_instance.stubs(:set_initial_state)
@order = Factory(:order, :state => "other_state")
end
...
end
Original Question
I am currently running the Acts As State Machine Rails Plugin (has been a huge time saver, incidentally) and having some challenges using it with Factory Girl (also wonderful).
I want to be able to set the object state when I create the object with Factories. A generalized way of asking this question is "how do you call class methods when creating a object with Factories?"
class Transporter < ActiveRecord::Base
validates_presence_of :company_name, :on => :update
acts_as_state_machine :initial => :created, :column => 'status'
state :created
state :active
state :inactive, :after => :inactivate_transporter_activity
end
Factory.define :transporter do |f|
f.sequence(:company_name) {|n| "transporter_company#{n}"}
end
>> t=Factory(:transporter)
=> <Transporter ... status: "created">
>> t=Factory(:transporter, :status => 'active')
=> <Transporter ... status: "created"> #as expected, changes state back
>> t.activate!
=> true
>> t
=> <Transporter ... status: "active">
I can always call the t.activate! method within every test, but this will make my tests brittle. I'm looking for a way to run this method at Factory creation level or set it within factory.rb.
Thanks...
发布评论
评论(1)
您可以使用模拟框架(mocha)来覆盖 set_initial_state 并获取对象的正确状态。
从 这里。
You can use a mocking framework (mocha) to override set_initial_state and get the correct state on your object.
Idea stolen from here.