[rspec-users] Setting instance variables for controllers

Maurício Linhares mauricio.linhares at gmail.com
Wed Sep 3 10:40:51 EDT 2008


You don't need to set the instance variable, you can stub the find call:

describe CartController do

 describe "index" do

  before do
    @user = mock_model( User )
  end

   it "should render 'cart_full' if @user is set" do
     # This is where I need to set @user
     User.stub!( :find ).with('your-id-param-here').and_return( @user )
     response.should render_template( : cart_full )
   end

   it "should render 'cart_empty' if @user is not set" do
     response.should render_template( : cart_empty )
   end

 end

end


On Wed, Sep 3, 2008 at 11:22 AM, patrick_r <patrickdavidreiner at gmail.com> wrote:
>
> Hi everyone,
>
> I have been trying to find an answer to this question and have not been able
> to. Any help is greatly appreciated.
>
> I am using Rails 2.1.0 and Rspec 1.1.4.
>
> How can I set an instance variable in my Rspec test that is then available
> to my controller while the test is running? For example:
>
> (I tried to keep this as simple as possible while illustrating what I mean)
>
>
> ---application_controller.rb---
>
> ApplicationController
>
>  before_filter :set_user
>
>  def set_user
>    @user = User.find( 5 )
>  end
>
> end
>
>
> ---cart_controller.rb---
>
> CartController
>
>  def index
>    if @user
>      render :action => 'cart_full'
>    else
>      render :action => 'cart_empty'
>    end
>  end
>
> end
>
>
> ---Rspec---
>
> describe CartController do
>
>  describe "index" do
>
>    it "should render 'cart_full' if @user is set" do
>      # This is where I need to set @user
>      response.should render_template( : cart_full )
>    end
>
>    it "should render 'cart_empty' if @user is not set" do
>      response.should render_template( : cart_empty )
>    end
>
>  end
>
> end
>
>
>
> Is this even possible to do?
>
> I thought that controller.set_instance_variable( :@user, ... ) would do the
> trick but it does not seem to work.
>
> Thank you!
> --
> View this message in context: http://www.nabble.com/Setting-instance-variables-for-controllers-tp19283500p19283500.html
> Sent from the rspec-users mailing list archive at Nabble.com.
>
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users
>



-- 
Maurício Linhares
http://alinhavado.wordpress.com/ (pt-br) | http://blog.codevader.com/ (en)
João Pessoa, PB, +55 83 8867-7208


More information about the rspec-users mailing list