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

David Chelimsky dchelimsky at gmail.com
Wed Feb 17 09:11:17 EST 2010


On Wed, Feb 17, 2010 at 8:03 AM, Nickolay Kolev <nmkolev at gmail.com> wrote:
>> I don't see @new_course getting defined anywhere. Try assigning it a
>> non-nil value in each of the POST examples (or in before(:each) in
>> that group).
>
> Thanks, David!
>
> Am I right in assuming that I have to check that @new_course received
> a "save" and returned true in the same it-block?
>
> This works:
>
> it "should build the new course" do
>
> @teacher.courses.should_receive(:build).with(@valid_course_attributes).and_return(@new_course)
>  @new_course.should_receive(:save).and_return(true)
>  do_post
> end

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. The reason this is working in this
case is that @new_course == nil, so and_return(@new_course) is
returning nil and then @new_course.should_receive(:save) is telling
nil to expect :save.

> This does not (naturally):
>
> it "should build the new course" do
>
> @teacher.courses.should_receive(:build).with(@valid_course_attributes).and_return(@new_course)
>  do_post
> end
>
> it "should build the new course" do
>  @new_course.should_receive(:save).and_return(true)
>  do_post
> end
>
> Is there a way to propagate the @new_course instance variable to the
> next it-block?

Nope. But you can define @new_course before(:each) example:

  before(:each) { @new_course = stub_model(Course) }

Then it will be non-nil and all should be well.

That all make sense?

David


More information about the rspec-users mailing list