Dudo
Dudo

Reputation: 4169

RSpec 3 undefined method `allow' for #<RSpec::Core::ExampleGroup...>

describe '#messages' do
  subject do
    FactoryGirl.create :foo,
      :type => 'test',
      :country => 'US'
  end

  context 'when is not U.S.' do
    before{ allow(subject).to receive(:country).and_return('MX') }

    describe '#messages' do
      subject { super().messages }
      it { is_expected.to include 'This foo was not issued in the United States of America.' }
    end
  end
end

I'm trying to assign an attribute on the subject... I can't seem to get the incantation correct. Do I need a Double here? I'm not sure how that even works, and I apparently can't decipher the docs. Any help is appreciated.

Upvotes: 5

Views: 1878

Answers (2)

Daniel Ruiz
Daniel Ruiz

Reputation: 620

I think you should define the subject variable as a helper method using let. With this, you are defining a helper method that you can use everywhere in the file.

So, I'll modify your code as follows:

describe '#messages' do
  let(:subject) do
    FactoryGirl.create :foo,
      :type => 'test',
      :country => 'US'
  end

  context 'when is not U.S.' do
    before{ allow(subject).to receive(:country).and_return('MX') }

    describe '#messages' do
      subject { super().messages }
      it { is_expected.to include 'This foo was not issued in the United States of America.' }
    end
  end
end 

Upvotes: 1

Taryn East
Taryn East

Reputation: 27747

I think the problem here is one of scope. you are calling the code in the before block before you've set up a subject

you'll need to either move the subject out into the outer context, move the before into the inner describe, or set up some alternative way of calling it so that subject is set up before running the before

Upvotes: 0

Related Questions