【发布时间】:2018-10-04 22:26:25
【问题描述】:
我正在将一个遗留项目升级到 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=#<ActionController::TestRequest:0x00007fbe5fde5358 ...>>>>.redirect?` to return true, got false
# ./spec/controllers/search_controller_spec.rb:86:in `block (3 levels) in <top (required)>'
我正在使用 devise gem 来验证客户端。
测试如下:
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,我会被重定向到登录页面。 search_controller.rb 有一个 before_action :authenticate_client!
我尝试在搜索前添加sign_out @client,但没有成功。
还尝试了current_client.reload,但无法识别 current_client。
在经过身份验证的搜索测试中,有一个对 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!
也尝试了here的建议,但没有奏效
正在测试的搜索控制器:
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
谢谢!
【问题讨论】:
-
您需要在问题中包含正在测试的控制器。
-
试试这个:
get :search, params: { q: "tec" }, format: :json, headers: {}, env: {}想法是重置标头,因为标头保留会话令牌、cookie 等。或者在行上方使用get执行此操作:cookies.delete(:remember_token)token 你必须检查浏览器中cookie的名称。 -
@max 将搜索控制器包含在问题中
-
@num8er 都试过了。第一个我得到
unknown keywords: headers, env,第二个也给我一个错误,我把它改成cookies.delete(:remember_token)没有错误,但测试一直失败 -
@marimaf 您确定身份验证检查器有效吗?就像您打开隐身浏览器并在没有身份验证的情况下进行搜索一样。也尝试设置错误的密码并检查您的测试是否通过
标签: ruby-on-rails rspec devise ruby-on-rails-5