November 18

acts_as_state_machine (AASM) and factory_girl

I was having trouble with initial states and factories on a recent project. I wanted to set the state of a factory object, but no matter what, it would be overwritten immediately.

The easiest solution I found is stubbing out set_initial_state on whatever model is carrying the state.

For example, if Order had state. In our order test:

require 'mocha'
class OrderTest < ActiveSupport::TestCase
  def setup
    Order.any_instance.stubs(:set_initial_state)
    @order = Factory(:order, :state => "other_state")
  end

  ...
end

Now, when you create your factory, the state will be set to whatever you pass it.