mercredi 27 janvier 2016

How stub a method on a model copy in rspec?

Say I have the next code:

class Foo < ActiveRecord::Base

  def self.bar
    all.map(&:bar)
  end

  def bar
    # do something that I want stub in test
  end
end

Now I want to create test (Rspec):

foo = Foo.create
expect(foo).to receive(:bar)
Foo.bar

This test does not pass because Foo.bar calls other instance of the same model foo.

I wrote some complex code in such situations before, like:

expect_any_instance_of(Foo).to receive(:bar)

but this is not good, because there are no confidence that foo receives message (there could be several instances). And also expect_any_instance_of is not recommended by Rspec maintainers.

How do you test such code, is any best practice?

Aucun commentaire:

Enregistrer un commentaire