aasm icon indicating copy to clipboard operation
aasm copied to clipboard

Describe how to use it with factory_bot

Open edusantana opened this issue 8 years ago • 6 comments

I use Factory_bot with rspec.

How can I create an object with different state other the initial?

class Job
  include AASM

  aasm do
    state :sleeping, :initial => true
    state :running, :cleaning

    event :run do
      transitions :from => :sleeping, :to => :running
    end

    event :clean do
      transitions :from => :running, :to => :cleaning
    end

    event :sleep do
      transitions :from => [:running, :cleaning], :to => :sleeping
    end
  end
end

How to define a factory to create objects with different states?

FactoryBot.define do
  factory :job do

    factory :job_running do
      # how can I create a job with the state runing?

    end
    factory :job_cleaning do
      # how can I create a job with the state cleaning?

    end

  end
end

edusantana avatar Jan 13 '18 14:01 edusantana

I there a better way then this:

FactoryBot.define do
  factory :job do

    factory :job_running do
      # is there a better way?
      after(:build) { |job| job.run }
    end
    factory :job_cleaning do
      # is there a better way?
      after(:build) do |job|
         job.run
         job.clean
      end 
    end

  end
end

edusantana avatar Jan 13 '18 14:01 edusantana

(ActiveRecord) You can create instance with any aasm state.

job = Job.new
job.save
# => #<Job id: 1, aasm_state: 'sleeping' >

job = Job.new(aasm_state: 'running')
job.save
# => #<Job id: 2, aasm_state: 'running' >

pashagray avatar Jan 26 '18 16:01 pashagray

@PavelTkachenko Factory_bot doesn't work that way. It creates the object for us setting many values. Supose the Job has more attributes, the factory will set those for us.

So, my question reamins, how to set a state after the object creation. Is there a way to set it?

edusantana avatar Jan 27 '18 22:01 edusantana

Callbacks are probably the only way I can see to do that with factory_bot/girl. Please try and use SOF for questions like this as it's not really a code issue.

darrenterhune avatar Apr 16 '18 16:04 darrenterhune

@edusantana I think you can use traits for setting aasm_state value.

anilmaurya avatar Apr 18 '18 03:04 anilmaurya