Karol Selak
Karol Selak

Reputation: 4794

How to filter out one method call from many others with `expect().to receive()` in RSpec

I have such a code:

class ClassB
  def print_letter(arg)
  end
end

class ClassA
  def self.my_method
    ClassB.print_letter("a")
    ClassB.print_letter("b")
  end
end

RSpec.describe ClassA do
  describe "self.my_method" do
    it "prints a" do
      allow(ClassB)
      expect(ClassB).to receive(:print_letter).once.with("a")
      described_class.my_method
    end
  end
end

And I'm getting a failure:

#<ClassB (class)> received :print_letter with unexpected arguments
  expected: ("a")
       got: ("b")

Can I do anything with that? Is there any way to force the receive method to analyze all method calls and pick the one where arguments match, not only the last one? BTW, this behavior seems confusing to me.

Upvotes: 0

Views: 100

Answers (1)

morissetcl
morissetcl

Reputation: 564

It's a good practice to give one responsability to one method.

In your case I guess you would like to test that your method return "A" and also "B".

I will recommend you to write a method which will return "A" And another one which return "B".

def print_a
  ClassB.print_letter("a")
end

def print_b
  ClassB.print_letter("b")
end

def self.my_method
    print_a
    print_b
  end

And then just test your methods separatly, for example:

it " Print a" do
  expect(print_a).to eq 'a'
end

In this way you don't need to test your self.my_method, it will Be overkill.

Upvotes: 1

Related Questions