Is there a way that I can stub all the calls to a method except from the first one?

12 views
Skip to first unread message

Panayotis Matsinopoulos

unread,
May 16, 2014, 2:18:48 AM5/16/14
to rs...@googlegroups.com
Hi,

Is there a way that I can stub all the calls to a method except from the first one?

Example:

    class Book
      def foo
        "Book#foo()"
      end
    end

In spec:

    it 'x' do
      # .... (do something to stub all but the first method call to `Book#foo`)....

      b = Book.new
      expect(b.foo).to eq('Book#foo()')
      expect(b.foo).to be_nil
      expect(b.foo).to be_nil
    end

Thanks in advance
Panayotis

Aaron Kromer

unread,
May 16, 2014, 4:23:25 PM5/16/14
to rs...@googlegroups.com

Can you provide a more concrete example? In general, this would make me a bit uneasy about what is either being tested or how the system is joined together.

If you there are no side effects and you just have a basic value, why not just stub the basic return?

class Foo
  def hello
    :foo
  end
end

it do
  f = Foo.new

  allow(f).to receive(:hello).and_return(:foo, nil)

  expect(f.hello).to be :foo
  expect(f.hello).to be nil
  expect(f.hello).to be nil

end

If there are no side effects, but something needs to be calculated first, possibly call it first?

it do

  f = Foo.new

  allow(f).to receive(:hello).and_return(f.hello, nil)

  expect(f.hello).to be :foo
  expect(f.hello).to be nil
  expect(f.hello).to be nil

end

Otherwise, it’s probably best for you to fall back to Ruby and just define a singleton method:

it do
  f = Foo.new
  f.define_singleton_method(:hello) do
    return if @already_called
    @already_called = true
    super()  # parens are necessary to make Ruby happy
  end

  expect(f.hello).to be :foo
  expect(f.hello).to be nil
  expect(f.hello).to be nil
end

Maybe someone else has some other ideas here.



--
You received this message because you are subscribed to the Google Groups "rspec" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rspec+un...@googlegroups.com.
To post to this group, send email to rs...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rspec/7f733801-34aa-47a7-ba47-bba303fe9c34%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages