I have controller method that uses redirect_to :back
to redirect the user back to the original page. The method is given below.
def create
@conversation = Conversation.find(params[:conversation_id])
@message = @conversation.messages.build(message_params)
if @message.save
undeletion_unread
redirect_to :back
flash[:success] = "Message Sent Successfully"
else
redirect_to :back
flash[:danger] = 'Message must be between 1-600 characters'
end
end
I am trying to write an integration test for the valid and invalid create method. The integration tests are given below.
test "valid creation of a message" do
post user_conversation_messages_path(@user, @conversation), message: {body: "abc"}
assert_equal "Message Sent Successfully", flash[:success]
end
test "invalid creation of a message" do
post user_conversation_messages_path(@user, @conversation), message: {body: " "}
assert_equal "Message must be 1-600 characters", flash[:success]
end
I get the following error associated with the redirect_to :back
.
Error:
MessageCreateTest#test_invalid_creation_of_a_message:
ActionController::RedirectBackError: No HTTP_REFERER was set in the request to this action, so redirect_to :back could not be called successfully. If this is a test, make sure to specify request.env["HTTP_REFERER"].
app/controllers/messages_controller.rb:14:in `create'
test/integration/message_create_test.rb:16:in `block in <class:MessageCreateTest>'
I have tried using the HTTP REFERRER(given below) instead of redirect_to :back in the create method but I still get the error.
redirect_to request.env["HTTP_REFERER"]
I am not sure what I need to change to pass the test of redirect_to :back. I ran into this problem once and I ended up changing the route. However, It is much easier to use redirect_to :back in this case. I have tried the different suggestions after I googled the problem. Most of them are outdated and don't really apply. Thanks