[rspec-users] Errors in controller test

Maurício Linhares
Sun, 20 Jul 2008 13:52:42 -0000

You are stubbing the wrong method, try this:

   before(:each) do
     login_user #login helper, stub login_requered and return @user
     @voting = mock_model(Voting)
     Voting.stub!(:new).and_return( @voting )
   end

On Sun, Jul 20, 2008 at 9:50 AM, cheef <cheef at list.ru>
wrote:
>
> I catch very strange error while testing:
>
> NoMethodError in ''VotingsController handling POST /votings should
redirect
> to index if success''
> You have a nil object when you didn''t expect it!
> You might have expected an instance of ActiveRecord::Base.
> The error occurred while evaluating nil.save
>
> Strange, because I''m stub my @voting.
>
> This is my test:
>
> describe "handling POST /votings" do
>
>    before(:each) do
>      login_user #login helper, stub login_requered and return @user
>      @voting = mock_model(Voting)
>      controller.stub!(:create_voting).and_return @voting
>    end
>
>    def do_post
>      post :create
>    end
>
>    it "should redirect to index if success" do
>      @voting.stub!(:save).and_return true
>      do_post
>      response.should redirect_to(votings_path)
>    end
>
>    #something else
>
>  end
>
> And there is my controller:
>
> class VotingsController < ApplicationController
>  before_filter :create_voting, :only => [:create]
>
>  #some stuff there
>
>  def create
>    respond_to do |format|
>      if @voting.save
>       ...
>      end
>    end
>  end
>
>  private
>
>  def create_voting
>    @voting = Voting.new(params[:voting])
>    @voting.author = current_user
>  end
>
> end
>
> P.S. but this tested fine
>
> def create
>    @voting = Voting.new(params[:voting])
>    @voting.author = current_user
>    respond_to do |format|
>      if @voting.save
>       ...
>      end
>    end
>  end
> --
> View this message in context:
http://www.nabble.com/Errors-in-controller-test-tp18358354p18358354.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