Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stub Model Save Method in Rspec/Rails

This should be simple, but i can't get it to work. I want to stub an :

@alliance.save

so that it returns true. I tried :

Alliance.stub(:save).and_return(true)

but it won't work. Any ideas ?

like image 358
Spyros Avatar asked Apr 03 '11 23:04

Spyros


3 Answers

If I'm not mistaken, Alliance.stub(:save) would affect calls to Alliance.save. You want @alliance.stub(:save).and_return(true).

Mocha has a useful method any_instance, so you could do something like Alliance.any_instance.stubs(:save).returns(true), which would (as the name implies) stub the save method for any instance of Alliance.

like image 94
Michelle Tilley Avatar answered Sep 18 '22 10:09

Michelle Tilley


Using the new RSpec syntax:

allow_any_instance_of(Alliance).to receive(:save).and_return(true)
like image 43
Dennis Avatar answered Sep 20 '22 10:09

Dennis


You're probably looking for something like:

describe AllianceController do
  let(:alliance) { mock_model(Alliance) }

  describe "#<controller action>" do
    before do
      Alliance.stub :new => alliance
    end

    context "valid alliance" do
      before do
        alliance.stub :save => true
      end

      it "should ..." do

      end
    end
  end
end

The inner context allows you to work with an Alliance mock which has the save method stubbed to return true.

like image 26
clemensp Avatar answered Sep 19 '22 10:09

clemensp