[rspec-users] Stubbing @instance.association.build

David Chelimsky dchelimsky at gmail.com
Wed Feb 17 10:44:07 EST 2010


On Wed, Feb 17, 2010 at 8:31 AM, Nickolay Kolev <nmkolev at gmail.com> wrote:
>> This is not working for the reason that I think you think it's
>> working. and_return is not an expectation - it is a command telling
>> @teacher to return @new_course when it receives :build. You have to
>> define @new_course in the spec.
>
> I did the following:
>
> http://gist.github.com/306521
>
> and it works as expected. make_unsaved is a class method added by
> Machinist.
>
> What is the scope of instance variables defined in a before(:each)
> block? They are available to all it-blocks, yet changes made to an
> instance variable in one it-block are reverted before the next one,
> correct?

Close, but not exactly. Each example is run in its own world. Any
before(:each) blocks are run before each example in the same world, so
the instance variables are not shared in any way at all from example
to example. So the following will pass if examples are run in any
order:

before(:each) { @foo = 1 }
it("does something") { @foo +=1; @foo.should == 2}
it("does something else") { @foo.should == 1 }

You _can_ run a before block only once by using before(:all), but that
leads to all sorts of problems related to state-sharing across
examples and should generally be avoided.

HTH,
David


More information about the rspec-users mailing list