37
33

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.

rspecでafter_commitのテスト

Last updated at Posted at 2013-05-10

概要

  • rspecのデフォルトの設定では、データベースへのコミットが行われないようになっているため、after_commitのテストができない
  • テストする方法をメモしておく

特定のテストだけcommitする

run_callbacksを使う


describe User do
  before do
    User.create!(name: "hoge")
    @user_id = User.last.id
  end

  it 'should output logs' do
    Rails.logger.should_receive(:warn).with(/hoge/o)
    user = User.find_by_id(@user_id)
    user.destroy
    user.run_callbacks(:commit)
  end
end

すべてのテストでcommitする

config.use_transactional_fixtures = false にする

  • ロールバックは自分でする必要がある

# spec_helper.rb

# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = false

参考

37
33
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
37
33

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?