Describe how to use it with factory_bot
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
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
(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' >
@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?
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.
@edusantana I think you can use traits for setting aasm_state value.