[rspec-users] set expectation using self in constructor?

Chuck Remes cremes.devlist at mac.com
Wed Jul 14 10:26:44 EDT 2010


I find myself using this pattern quite a bit.

rspec 1.30
ruby 1.9.1, 1.9.2-rc2, jruby 1.51 all on osx 10.6.4

class Foo
  def initialize
    @bar = Bar.new
  end
end

context "init" do
  it "should allocate a helper class Bar" do
    Bar.should_receive(:new)
    Foo.new
  end
end

That all works well and as expected. Where I get stuck is when I change the signature for Bar to accept an argument from Foo like so:

class Foo
  def initialize
    @bar = Bar.new self
  end
end

# try 1
context "init" do
  it "should allocate a helper class Bar" do
    Bar.should_receive(:new).with(self)  # self refers to rspec here
    Foo.new
  end
end

# try 2
context "init" do
  let(:foo) { Foo.new }

  it "should allocate a helper class Bar" do
    Bar.should_receive(:new).with(foo)  # foo is a different instance
    Foo.new
  end
end

# try 3
context "init" do
  it "should allocate a helper class Bar" do
    Bar.should_receive(:new).with(instance_of(Foo)) # works but seems wrong
    Foo.new
  end
end

I have tried lots of techniques for setting an argument expectation in my spec, but none of them work completely. How do others solve this? Or have I discovered a spec anti-pattern?

If this is an anti-pattern, what is the suggested programming technique to avoid it?

cr



More information about the rspec-users mailing list