UFO ET IT

Rspec 테스트 redirect_to : back

ufoet 2020. 11. 30. 20:26
반응형

Rspec 테스트 redirect_to : back


redirect_to :backrspec에서 어떻게 테스트 합니까?

나는 얻다

ActionController::RedirectBackError: 이 작업에 대한 요청에
아니요 HTTP_REFERER가 설정되어 있으므로 redirect_to :back성공적으로 호출 할 수 없습니다. 테스트 인 경우를 지정해야 request.env["HTTP_REFERER"]합니다.

HTTP_REFERER테스트에서 어떻게 설정 합니까?


RSpec을 사용하여 before블록 에서 참조자를 설정할 수 있습니다 . 테스트에서 직접 리퍼러를 설정하려고했을 때 어디에 넣어도 작동하지 않는 것 같았지만 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

새로운 요청 스타일로 요청을 요청할 때 Rails 가이드 에서 :

describe BackController < ApplicationController do
  describe "GET /goback" do
    it "redirects back to the referring page" do
      get :show, 
        params: { id: 12 },
        headers: { "HTTP_REFERER" => "http://example.com/home" }
      expect(response).to redirect_to("http://example.com/home")
    end
  end
end

누군가 이것을 우연히 발견하고 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

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


통합 테스트에서 : back 링크를 테스트하는 것과 관련하여 먼저 링크로 사용되지 않을 것 같은 막 다른 페이지를 방문한 다음 테스트중인 페이지를 방문합니다. 그래서 내 코드는 다음과 같습니다.

   before(:each) do
       visit deadend_path
       visit testpage_path
    end
    it "testpage Page should have a Back button going :back" do
      response.should have_selector("a",:href => deadend_path,
                                        :content => "Back")
    end

그러나 이것은 링크가 실제로 deadend_path에 대한 것이라면 테스트가 잘못 통과 할 것이라는 결점을 가지고 있습니다.


IMHO the accepted answer is a bit hacky. A better alternative would be to set the HTTP_REFERER to an actual url in your application and then expect to be redirected back:

describe BackController, type: :controller do
  before(:each) do
    request.env['HTTP_REFERER'] = root_url
  end

  it 'redirects back' do
    get :whatever
    response.should redirect_to :back
  end
end
  • Redirecting to a random string constant feels as if it works by accident
  • You take advantage of rspec's built in functionality to express exactly what you wanted
  • You don't introduce and repeat magic string values

For newer versions of rspec, you can use expectations instead:

expect(response).to redirect_to :back

request.env['HTTP_REFERER'] = '/your_referring_url'

참고URL : https://stackoverflow.com/questions/6040479/rspec-testing-redirect-to-back

반응형