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

Matt Wynne matt at mattwynne.net
Wed Jul 14 17:20:49 EDT 2010


On 14 Jul 2010, at 15:26, Chuck Remes wrote:

> 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?

You can do this, by using a test spy to remember the value of foo passed into the stubbed constructor and then later comparing it:

let(:foo) { Foo.new }

it "should allocate a helper class Foo" do
  actual_foo = Bar.should_receive(:new) do |the_foo|
    the_foo
  end
  actual_foo.should == foo
end
  
Whether you want to do this though, is another question. I think it's a bit of an anti-pattern personally. I'd probably let acceptance tests catch mistakes in this kind of thing, and concentrate on speccing the interaction between Foo and Bar once you've got the instances spun up.

> 
> cr
> 
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users

cheers,
Matt

http://blog.mattwynne.net
+44(0)7974 430184



More information about the rspec-users mailing list