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 .
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?
The following code is for RSpec > 2.1 and it uses the expect
syntax.
before(:each) do
@params = valid_attributes
end
it "should create new user" do
@_before = User.count
post :create, :user => @params
expect(assigns(:user)).to_not be_new_record
expect(User.count).to eq(@_before + 1)
end
it "should render the success page on successful signup" do
post :create, :user => @params
expect(response).to be_successful
expect(response).to render_template("success")
end
Finally, change
render :template => "success"
to
render :action => "success"
For previous RSpec versions or if you have to use the should
syntax, use
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With