I'm stuck on a test scenario.
I have a controller method:
def update
@object = Object.find params[:id]
# some other stuff
@object.save
rescue ActiveRecord::StaleObjectError
# woo other stuff
end
The first part I test with:
context '#update'
let(:object) { double }
it 'nothing fails' do
# some other stuff
expect(Object).to receive(:find).with('5').and_return(object)
expect(object).to receive(:save).and_return(true)
xhr :put, :update, id:5
expect(response).to be_success
expect(assigns(:object)).to eq(object)
end
end
Now I want to test the ActiveRecord::StaleObjectError
exception. I want to stub it, but I didn't find any solution how to do this.
So my question is, how to raise the ActiveRecord::StaleObjectError
in an RSpec test?
Mocking is a technique in test-driven development (TDD) that involves using fake dependent objects or methods in order to write a test. There are a couple of reasons why you may decide to use mock objects: As a replacement for objects that don't exist yet.
RSpec is a Behavior-Driven Development tool for Ruby programmers. BDD is an approach to software development that combines Test-Driven Development, Domain Driven Design and Acceptance Test-Driven Planning. RSpec helps you do the TDD part of that equation, focusing on the documentation and design aspects of TDD.
RSpec features doubles that can be used as 'stand-ins' to mock an object that's being used by another object. Doubles are useful when testing the behaviour and interaction between objects when we don't want to call the real objects - something that can take time and often has dependencies we're not concerned with.
Like this, for example
expect(object).to receive(:save).and_raise(ActiveRecord::StaleObjectError)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With