'Rspec test fails while rendering
For my user controller, while running the test cases I am facing render issue. It is redirecting to http://test.host/sign_in instead of rendering new.
- Controller code
def create
@user = User.new(user_params)
respond_to do |format|
if @user.save
UserMailer.registration_confirmation(@user).deliver_now
session[:user_id] = @user.id
format.html { redirect_to sign_in_path, notice: 'User was successfully created.' }
format.json { render :show, status: :created, location: @user }
else
format.html { render :new }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
- spec/users_controller_spec.rb
describe '#create' do
it 'User created' do
new_user = FactoryBot.build :user
post :create, params: {
user: {
id: new_user.id,
firstname: new_user.firstname,
email: new_user.email,
password: "s",
password_confirmation:"s"
}
}
expect(response).to render_template("new")
end
end
While running this test case I am facing this error!
- Error
Failures:
1) UsersController controller test cases #create User created
Failure/Error: expect(response).to render_template("new")
expecting <"new"> but was a redirect to <http://test.host/sign_in>
# ./spec/controllers/users_controller_spec.rb:30:in `block (4 levels) in <top (required)>'
How do I resolve this?
Solution 1:[1]
According to your controller code, you redirect to sign_in when the save is successful :
format.html { redirect_to sign_in_path, notice: 'User was successfully created.' }
Your failing test is saying :
expecting <"new"> but was a redirect to <http://test.host/sign_in>
It comes from expect(response).to render_template("new")
. You might want to change this line to expect(subject).to redirect_to(sign_in_path)
.
The behaviour render_template("new")
might be relevant when @user.save
is false
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Raphael Pr |