Rspec测试redirect_to:返回

Cyr*_*rus 62 redirect rspec ruby-on-rails rspec2

你如何redirect_to :back在rspec中测试?

我明白了

ActionController::RedirectBackError:在此操作的请求中设置了
No HTTP_REFERER,因此redirect_to :back无法成功调用.如果这是测试,请确保指定request.env["HTTP_REFERER"].

我如何设置HTTP_REFERER我的测试?

jos*_*arh 113

使用RSpec,您可以在before块中设置引用.当我试图直接在测试中设置引用时,无论我把它放在哪里它似乎都不起作用,但是前面的块可以解决问题.

describe BackController < ApplicationController do
  before(:each) do
    request.env["HTTP_REFERER"] = "where_i_came_from"
  end

  describe "GET /goback" do
    it "redirects back to the referring page" do
      get 'goback'
      response.should redirect_to "where_i_came_from"
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

  • 我发现使用它是个好主意:`request.env ["HTTP_REFERER"] ="where_i_came_from"除非request.nil?或者request.env.nil?` (4认同)

sp8*_*p89 5

如果有人偶然发现这一点并且他们正在使用request规范,则您需要在您发出的请求上显式设置标头。测试请求的格式取决于您使用的 RSpec 版本以及是否可以使用关键字参数而不是位置参数。

let(:headers){ { "HTTP_REFERER" => "/widgets" } }

it "redirects back to widgets" do 
  post "/widgets", params: {}, headers: headers # keyword (better)
  post "/widgets", {}, headers                  # positional

  expect(response).to redirect_to(widgets_path)
end
Run Code Online (Sandbox Code Playgroud)

https://relishapp.com/rspec/rspec-rails/docs/request-specs/request-spec