On Wed, Jul 14, 2010 at 10:26 AM, Chuck Remes <cremes.devl...@mac.com> 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?
The problem is that the instance of Foo that you are testing for doesn't exist until you call Foo.new. I'd change this to spec the results rather than the implementation: e.g. foo = Foo.new foo.bar.should == foo Assuming that foo and bar have public accessors for bar and foo respectively. If not you can use instance_variable_get to 'get' around that. HTH -- Rick DeNatale Blog: http://talklikeaduck.denhaven2.com/ Github: http://github.com/rubyredrick Twitter: @RickDeNatale WWR: http://www.workingwithrails.com/person/9021-rick-denatale LinkedIn: http://www.linkedin.com/in/rickdenatale _______________________________________________ rspec-users mailing list rspec-users@rubyforge.org http://rubyforge.org/mailman/listinfo/rspec-users