我一直对此低头,觉得我可能犯了一个简单的错误,但我无法找到关于这个问题的任何信息。
我有一些 Rails 5 的请求规范,当我测试重定向时——但不是渲染模板——我得到一个错误,undefined method 'response_code' for nil:NilClass
. 原因似乎@response
是nil
在调用匹配器时(在 ActionDispatch::Assertions::ResponseAssertions 代码中,而不是在我的代码中)。我可以使用 cURL 向 API 发出请求,它会按预期返回响应。返回错误的地方在这里(这是 ActionDispatch 代码):
def generate_response_message(expected, actual = @response.response_code)
"Expected response to be a <#{code_with_name(expected)}>,"\
" but was a <#{code_with_name(actual)}>"
.dup.concat(location_if_redirected).concat(response_body_if_short)
end
请注意第一行,其中actual
参数的默认值设置为@response.response_code
.
这是我的测试代码:
RSpec.describe "Admin registrations", type: :request do
describe "new sign-up" do
subject { get new_admin_registration_path }
it "redirects to home" do
expect(subject).to redirect_to(new_admin_session_path)
end
end
end
测试日志中的相关行是:
Started GET "/admins/sign_up" for 127.0.0.1 at 2018-07-05 10:44:05 -0700
Processing by Admins::RegistrationsController#new as HTML
Redirected to http://example.org/admins/sign_in
Completed 301 Moved Permanently in 18ms (ActiveRecord: 0.0ms)
有趣的是,当我使用 byebug 检查 的值时subject
,它确实返回了一个 Rack::MockResponse 对象,所以这在某种程度上没有通过。
非常感谢我能得到的任何帮助!