I am trying to test a controller create method in a rails app using RSpec as shown below:
def create
@user = User.new(user_params)
if @user.save
redirect_to user_path(@user.id)
else
render new_user_path
flash[:error] = "User not saved"
end
end
However if i stub out .new
to prevent the test from using Active Record and the User model by forcing it to return true
the id of the @user
is not set by .save
as normal so I cannot test for it redirecting to user_path(@user.id)
as @user.id
is nil
Here is my initial test for RSpec:
it "creates a user and redirects" do
expect_any_instance_of(User).to receive(:save).and_return(true)
post :create, { user: {name: "John", username: "Johnny98", email: "[email protected]"} }
expect(assigns(:user).name).to eq("John")
expect(response).to redirect_to user_path(assigns(:user))
end
How should I test for this redirect in RSpec.
You should use mocks - https://www.relishapp.com/rspec/rspec-mocks/docs.
Then you should mock you method with double you've just created
And then test redirect.
I hope this will help.