Rspec测试失败,truenthicate_client无法正常工作

我正在将遗留项目升级到rails 5,并且在失败的rspec测试中我有一个说:

Failure/Error: expect(response).to be_redirect expected `#<ActionDispatch::TestResponse:0x00007fbe5fde51f0 @mon_owner=nil, @mon_count=0, @mon_mutex=#<Thread::...ch::Http::Headers:0x00007fbe5fdde9e0 @req=#>>>.redirect?` to return true, got false # ./spec/controllers/search_controller_spec.rb:86:in `block (3 levels) in ' 

我正在使用devise gem来validation客户端。
测试如下:

 describe SearchController do before(:each) do @client = FactoryGirl.create(:client) end describe "authenticated search" do # a bunch of tests end describe "unauthenticated search" do it "requires a user to be authenticated" do get :search, params: { q: "tec" }, format: :json expect(response).to be_redirect # FAILING HERE end end end 

如果我手动运行测试并转到/search?q=tec我会被重定向到sign_in页面。 search_controller.rb有一个before_action :authenticate_client!

我尝试在搜索之前添加sign_out @client ,但它没有用。 还尝试了current_client.reload但没有识别出current_client。

在经过身份validation的搜索测试中,调用stub_authenticate_client ,其中包含以下代码:

  def stub_authenticate_client(client) allow(request.env['warden']).to receive(:authenticate!) { client } allow(controller).to receive(:current_client) { client } end 

如果这对解决这个问题很有帮助。

我也尝试过这样创建一个stub_logout_client方法:

  def stub_logout_client(client) allow(request.env['warden']).to receive(:authenticate!) { nil } allow(controller).to receive(:current_client) { nil } end 

并在测试开始时调用它,但它仍然传递before_action authenticate_client!

也尝试了这里建议,但没有奏效

正在测试的搜索控制器:

 class SearchController < ClientApplicationController before_action :authenticate_client! def search limit = params[:limit] ? params[:limit].to_i : 10 query = params[:q].to_s.downcase.strip results = {} if params[:report] results[:this_report] = Report.where("SOME QUERY") end render json: results end end 

谢谢!

该问题与be_redirect检查有关。 更改了测试以检查响应中的内容并解决了它,如下所示:

 describe "unauthenticated search" do it "requires a user to be authenticated" do get :search, params: { q: "tec" }, format: :json expect(response.body).to have_content("content from the page I render") end end