Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to raise an exception in an RSpec test

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?

like image 261
rob Avatar asked Sep 02 '15 13:09

rob


People also ask

What is mocking in RSpec?

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.

Is RSpec TDD or BDD?

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.

What is double in RSpec?

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.


1 Answers

Like this, for example

expect(object).to receive(:save).and_raise(ActiveRecord::StaleObjectError)
like image 93
Sergio Tulentsev Avatar answered Oct 11 '22 17:10

Sergio Tulentsev