[rspec-users] How to mock an object defined in the before_filter function?

David Chelimsky dchelimsky at gmail.com
Mon Feb 23 14:32:30 EST 2009


On Fri, Feb 20, 2009 at 10:17 AM, Evgeny Bogdanov
<evgeny.bogdanov at gmail.com> wrote:
> Hello,
>
> I am trying to implement the following scenario, but I am stuck ...
> The thing is I want to initialize a variable @comment when the stub
> function "find_comment" is called.
> The way I do it below doesn't work, since
> "before_filter :find_comment" returns true/false and @comment
> initialization is done inside it. Could you please give me a hint how
> to do it?
>
> One solution would be to use
> Comment.stub!(:find).and_return(@comment) and do not use the stub
> find_comment.

That's the way to do it.

> But how to do it in general, when there is no expression like "@var =
> my_var.function" in the controller and variable @var is defined in
> another place and controller just uses it.

In general, it's best to avoid dealing directly with internal state on
an object that you're specifying and only manipulate its state through
public methods and/or mocks/stubs on collaborators. So in this case,
I'd just stub Comment.find, as mentioned above.

> my_var.stub!(:function).and_return(@var) doesn't seem to be working.
>
> Is there is something like
> my_var.stub!(:function).add_variable(@var).and_return(:true)

Nope. For the reasons stated above. This is too invasive.

Cheers,
David

> ?
>
> Thank you,
> Evgeny
> =============controller_file
>  before_filter :find_comment, :only => [:destroy]
>
>  def destroy
>    @destroy_id = @comment.id #to be used in rendering partial
>    @comment.destroy
>
>    respond_to do |format|
>      format.js
>    end
>  end
>
>  def find_comment
>     @comment = Comment.find(:first, :conditions => ['id= ?',params
> [:comment_id]])
>  end
> ===============spec_file
> spec code
> describe CommentsController, "while deleting a comment" do
>  it "should render destroy.rjs in case of success" do
>    @comment = mock_model(Comment)
>    @comment.stub!(:id).and_return(1)
>    @comment.stub!(:destroy).and_return(:true)
>
>    controller.stub!(:find_comment).and_return(@comment)
>
>    # execute ajax request
>    request.env["HTTP_ACCEPT"] = "application/javascript"
>    post :destroy, :comment_id => 1, :item_id => 1, :item_type =>
> "Space"
>
>    response.should render_template("destroy")
>  end
> end
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users
>


More information about the rspec-users mailing list