fatfrog
fatfrog

Reputation: 2160

RSPEC - Expected vs Received Error

Here is my test:

describe Item do
  subject {Item.new(:report_id => 26 ,  :name => 'Gas' ,  :tax_rate => 0.13, :tax_id => 1 ,  :category_id => 15 ,  :sub_category_id => 31 ,  :job_id => 1 , :total => 20 )}

  let(:tax) {Tax.where(id: subject.tax_id).first}
  let(:sub_category) {SubCategory.where(id: subject.sub_category_id).first}


  it 'Calculate with just Total' do

    subject.name.should be == 'Gas'
    tax = Tax.find_by_id(subject.tax_id)
    subject.sub_category_id.should be == 31
    subject.set_nil_values
    sub_category.should_receive(:taxable).and_return(1)
    tax.should_receive(:rate).and_return(0.13)
    sub_category.should_receive(:tax_adjustment).and_return(nil)
    subject.should_receive(:tax_rate).and_return(0.13)
    subject.calculate_tax(tax, sub_category)
    subject.tax_amount = (((subject.total - subject.deduction) - ((subject.total - subject.deduction) / (1 + 0.13))) * 1)
    subject.calculate_cost
    subject.cost.should be_within(0.01).of(17.70)

  end

Here is my error:

  1) Item Calculate with just Total
     Failure/Error: subject.should_receive(:tax_rate).and_return(0.13)
       (#<Item:0x007faab7299c30>).tax_rate(any args)
           expected: 1 time with any arguments
           received: 3 times with any arguments
     # ./spec/models/item_spec.rb:25:in `block (2 levels) in <top (required)>'

I did some research, and tried to use this instead:

    expect_any_instance_of(subject).to receive(:tax_rate)

But now get the following error:

  1) Item Calculate with just Total
     Failure/Error: expect_any_instance_of(subject).to receive(:tax_rate)
     NoMethodError:
       undefined method `method_defined?' for #<Item:0x007fe6fdaa1bf8>
     # ./spec/models/item_spec.rb:25:in `block (2 levels) in <top (required)>'

Upvotes: 2

Views: 1999

Answers (1)

Peter Alfvin
Peter Alfvin

Reputation: 29389

Your initial error occurred because, as the error message stated, the method in question was called three times rather than once, which is the implicit expectation. Assuming the actual behavior is what it should be, you can change the expectation to be:

...receive(...).exactly(3).times

See http://rubydoc.info/gems/rspec-mocks/frames for more info.

As for the second error you encountered, based on my testing, this occurs when you use expect_any_instance_of with a class that already has an instance stubbed and then you call that stubbed instance. In any event, even if this had worked, I don't believe it's what you would have wanted, as the semantics in terms of frequency of expect_any_instance_of is the same as expect, namely "one (total) call across the stubbed instance(s)".

If this second error occurred without you having removed the existing expectation on subject, let me know.

Upvotes: 1

Related Questions