[rspec-users] Not sure why this is failing

Scott Taylor mailing_lists at railsnewbie.com
Sat Nov 17 23:06:47 EST 2007


On Nov 17, 2007, at 10:52 PM, Chris Olsen wrote:

> I am not sure why the tests don't see the call of the new method  
> for the
> Address class.  It can be seen in the controller method where the
> Address.new is called.
>>> @address = Address.new(params[:address])
>
> What am I doing wrong?
>

You probably want

Address.should_receive(:new).with(no_args).and_return @address

Generally, if you have these sorts of mock expectation errors you can  
write a more simple test by removing the "with" clause to see if the  
is the message is being received with any arguments.

Scott


> Thanks for the help.
>
> Here is the error message:
> Spec::Mocks::MockExpectationError in 'UsersController handling POST
> /users should create a new user'
> Mock 'Class' expected :new with ({}) once, but received it 0 times
> ./spec/controllers/users_controller_spec.rb:245:
> script/spec:4:
>
> ###################################
>
> describe UsersController, "handling POST /users" do
>
>   before do
>     @address = mock_model(Address, :to_param => "1")
>     @user = mock_model(User, :to_param => "1", :address => @address,
> :address= => nil)
>     User.stub!(:new).and_return(@user)
>     Address.stub!(:new).and_return(@address)
>   end
>
>   def post_with_successful_save
>     @user.should_receive(:save).and_return(true)
>     post :create, :user => {}
>   end
>
>   it "should create a new user" do
>     User.should_receive(:new).with({}).and_return(@user)
>     Address.should_receive(:new).with({}).and_return(@address)    <--
> Line 245
>     post_with_successful_save
>   end
>
> end
>
> ###################################
>
> class UsersController < ApplicationController
>
> def create
>     @user = User.new(params[:user])
>     @address = Address.new(params[:address])
>     @user.address = @address
>
>     respond_to do |format|
>       if @user.save
>         flash[:notice] = 'User was successfully created.'
>         format.html { redirect_to user_url(@user) }
>         format.xml  { head :created, :location => user_url(@user) }
>       else
>         format.html { render :action => "new" }
>         format.xml  { render :xml => @user.errors.to_xml }
>       end
>     end
>   end
> end
> -- 
> Posted via http://www.ruby-forum.com/.
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users



More information about the rspec-users mailing list