1
votes

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

1
@neydroid, I checkout the question prior to posting one. I am not sure what exactly is the solution proposing. Also, the answer is 5 years old. Many things have changed in rails and other things. It might not actually workDivjot Mehton
can you post your router config to give you an answer with an appropriate example?neydroid

1 Answers

0
votes

You need to set the HTTP_REFERER before doing any work with the routes, then you'll have where to go back like this:

test "valid creation of a message" do 
  request.env["HTTP_REFERER"] = "/posts"
  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 
  request.env["HTTP_REFERER"] = "/posts"
  post user_conversation_messages_path(@user, @conversation), message: {body: "  "}
  assert_equal "Message must be 1-600 characters", flash[:success]
end