[rspec-users] Stub activerecord find given instance?

David Chelimsky dchelimsky at gmail.com
Tue Jan 12 22:49:09 EST 2010


On Tue, Jan 12, 2010 at 6:58 PM, Saverio Miroddi <lists at ruby-forum.com>wrote:

> David Chelimsky wrote:
>
> >>> MyModel.stub(:find).with(42).and_return(myModel)
> >> Didn't work as expected - I'll do a bit of research and post again.
> > What is expected? What are you trying to accomplish?
>
> Example in horror-code:
>
> ##################################################
>
> class MyController < ApplicationController
>  def show
>    MyModel.find_by_code( params[:code] )
>    head :ok
>  end
> end
>
> describe "MySuite" do
>  it "should" do
>    MyModel.stub!( :find_by_code ).with( "abc" ) do
>      puts "triggered 'abc'!"
>    end
>
>    get :show, :code => "kkk"
>  end
> end
>
> ##################################################
>
> I'm expecting nothing to be printed, instead "triggered 'abc'!" is
> printed.
>

That's actually the expected behaviour. When you pass a block to a call to
stub, with, or and_return, the block is evaluated and the resulting value is
returned to the caller. So in the show method, when MyModel.find_by_code(
params[:code] ), the block in the example is invoked.

It'd be much easier to help you if you could provide an example more
representative of what you are actually trying to accomplish.


> The example is, as I said, completely meaningless, but would simplify
> some tests in our suites.
> --
> Posted via http://www.ruby-forum.com/.
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://rubyforge.org/pipermail/rspec-users/attachments/20100112/d3fe4fdd/attachment.html>


More information about the rspec-users mailing list