telecasterrok
telecasterrok

Reputation: 209

Rspec Stubbing Behavior

I'm having some trouble with stubs, and I think I must be misunderstanding how they work.

Do stubs only exist within the context that they are created? That is my expectation, but in my experience if I stub a method within a context it still exists in another context.

my controller test is similar to this:

describe '.load_articles' do
  context 'articles' do
    before(:each) do
      Article.stub_chain(:meth1, :meth2).and_return(['article'])
    end
    it 'sets articles' do
      controller.load_articles.should == ['article']
    end

  end
  context 'no articles' do
    before(:each) do
      Article.stub_chain(:meth1, :meth2).and_return([])
    end
    it 'sets article' do
      controller.load_articles.should == []
    end

  end
end

and for the second example controller.load_articles still returns ['article'] when I'm expecting []

I've been stuck on this for too long; any help is greatly appreciated!

Upvotes: 1

Views: 53

Answers (1)

zetetic
zetetic

Reputation: 47578

Stubs are cleared after each example. You can prove this pretty easily:

class Numero; end

describe Numero do
  context "Uno" do
    before do
      Numero.stub_chain(:meth1, :meth2) { 'uno' }
    end
    it "unos" do
      Numero.meth1.meth2.should == 'uno'
    end
  end
  context "Dos" do
    before do
      Numero.stub_chain(:meth1, :meth2) { 'dos' }
    end
    it "dosses" do
      Numero.meth1.meth2.should == 'dos'
    end
  end
end

Upvotes: 1

Related Questions