2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

FactoryGirlのcreateはafter commit callbackを実行しない

Last updated at Posted at 2014-11-02

FactoryGirlで create した場合、 after_commit だけ実行されない。

class Book < ActiveRecord::Base
  before_create do
    puts 'before_create'
  end

  after_create do
    puts 'after_create'
  end

  after_commit :run_something, on: :create

  private

  def run_something
    puts 'after_commit'
  end
end

FactoryGirl.define do
  factory :book
end

FactoryGirl.create(:book)
# => before_create
# => after_create

実行したい場合はcallbackを自分で実行しないといけない。例えば以下のようにすればいい。

FactoryGirl.define do
  factory :book do
    after(:create) do |book|
      book.__send__(:run_something)
    end
  end
end

FactoryGirl.create(:book)
# => before_create
# => after_create
# => after_commit
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?