views:

12

answers:

1

Im trying to test a condition where on successful signup a Success Template is rendered by the following controller code


def create
    @user = User.new(params[:user])
    if @user.save
      render :template => "success"
    else
      flash[:notice] = "Oops Somethings not quite right! :("
      render :action => "new"
    end
  end

I am using the following spec to test out this code


 before(:each) do
    @user = User.new
    @user.attributes = valid_attributes    
    @params = valid_attributes
    @user.stub!(:save).and_return(true)
  end


  def do_post
    post :create
  end


  it "should create new user " do
    count = User.count
    do_post
    user = User.new(@params)    
    user.save.should eql(true)
    User.count.should eql(count + 1)

  end

  it "should render the success page on successful signup" do
    do_post
    @user.save
    response.should render_template("success") if @user.save
  end

But the example fails "it should render success page on successful signup" with this error message


1)
'UsersController handling POST /users should render the success page on successful signup' FAILED
expected "success", got "users/new.html.erb"
./spec/controllers/users_controller_spec.rb:67:

The success view is an template stored in the views/users/ without an action. Im guessing im making a very fundamental mistake and would like some help .

+3  A: 

You are stubbing the @user variable in the test, but the controller will instantiate a new instance so the stub won't be in place.

It's not a good idea to use a stub in this case just to emulate a successful save call. Why don't you supply valid data instead and make sure the action is successful?

before(:each) do
  @params = valid_attributes
end

it "should create new user" do
  @_before = User.count
  post :create, :user => @params

  assigns(:user).should_not be_new_record
  User.count.should == (@_before + 1)
end

it "should render the success page on successful signup" do
  post :create, :user => @params

  response.should be_successful
  response.should render_template("success")
end

Finally, change

render :template => "success"

to

render :action => "success"
Simone Carletti
That was it. I just got it. Thank you. Im still in the process of understanding working with Rspec. Thank you very much.
Sid