class User < ActiveRecord::Base
before_create :test, if: -> { name == 'taro'}
def test
puts 'this is after create callback'
raise(StandardError)
end
end
require 'rails_helper'
describe 'User' do
describe 'test 1' do
before { User.skip_callback(:create, :before, :test) }
after { User.set_callback(:create, :before, :test) }
it do
user = User.create(name: 'taro')
expect(user.name).to eq 'taro'
end
end
describe 'test 2' do
context 'name is taro' do
it 'raised' do
expect { User.create(name: 'taro') }.to raise_error(StandardError)
end
end
context 'name is jiro' do
it 'not raised' do
expect { User.create(name: 'jiro') }.not_to raise_error
end
end
end
end
test2=>test1の場合は問題ないが…
$ bundle exec rspec -f d spec/models
Randomized with seed 63633
User
test 2
name is taro
this is after create callback
raised
name is jiro
not raised
test 1
should eq "taro"
Finished in 0.01446 seconds (files took 1.32 seconds to load)
3 examples, 0 failures
test1=>test2の場合は失敗する。
$ bundle exec rspec -f d spec/models
Randomized with seed 58258
User
test 1
should eq "taro"
test 2
name is taro
this is after create callback
raised
name is jiro
this is after create callback
not raised (FAILED - 1)
Failures:
1) User test 2 name is jiro not raised
Failure/Error: expect { User.create(name: 'jiro') }.not_to raise_error
expected no Exception, got #<StandardError: StandardError> with backtrace:
# ./app/models/user.rb:6:in `test'
# ./spec/models/user_spec.rb:23:in `block (5 levels) in <top (required)>'
# ./spec/models/user_spec.rb:23:in `block (4 levels) in <top (required)>'
# ./spec/models/user_spec.rb:23:in `block (4 levels) in <top (required)>'
Finished in 0.02744 seconds (files took 1.34 seconds to load)
3 examples, 1 failure
Failed examples:
rspec ./spec/models/user_spec.rb:22 # User test 2 name is jiro not raised
Randomized with seed 58258
require 'rails_helper'
describe 'User' do
describe 'test 1' do
before { allow_any_instance_of(User).to receive(:test) }
it do
user = User.create(name: 'taro')
expect(user.name).to eq 'taro'
end
end
describe 'test 2' do
context 'name is taro' do
it 'raised' do
expect { User.create(name: 'taro') }.to raise_error(StandardError)
end
end
context 'name is jiro' do
it 'not raised' do
expect { User.create(name: 'jiro') }.not_to raise_error
end
end
end
end