簡體   English   中英

測試redirect_to:返回rspec rails

[英]testing for redirect_to :back in rspec rails

我有控制器方法,使用redirect_to :back將用戶重定向回原始頁面。 該方法如下。

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

我正在嘗試為有效和無效的create方法編寫集成測試。 集成測試如下。

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

我收到與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>'

我已經嘗試在create方法中使用HTTP REFERRER(如下所示)而不是redirect_to:但我仍然得到錯誤。

redirect_to request.env["HTTP_REFERER"]

我不確定我需要更改以通過redirect_to:back的測試。 我遇到過這個問題一次,最后我改變了路線。 但是,在這種情況下使用redirect_to更容易。 我在谷歌搜索問題后嘗試了不同的建議。 他們中的大多數已經過時,並沒有真正適用。 謝謝

您需要在對路由進行任何工作之前設置HTTP_REFERER,然后您將有這樣的地方back

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM