【发布时间】:2018-07-04 23:44:17
【问题描述】:
我一直对此深有感触,觉得我可能犯了一个简单的错误,但我无法找到有关此问题的任何信息。
我有一些 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 对象,所以这在某种程度上没有通过。
非常感谢我能得到的任何帮助!
【问题讨论】:
-
嗯,规范看起来不错。有什么要分享的日志吗?另外,如果你改用
get 'somepath/someresource'会发生什么 -
get "somepath/someresource"给我一个路由错误。我在日志中没有看到任何异常,但我会在问题中添加内容。 -
对不起,我的意思是不要像你正在做的那样使用路径助手,不管
new_admin_registration_path的字符串是什么。 -
哦!我试过了,结果一样。
标签: ruby-on-rails rspec rack-test