我正在尝试测试未经授权的用户向我的Rails 4博客应用程序的Posts控制器发出的直接POST请求的结果。在 Rails 教程之后,我已经为 Users 控制器实现了功能测试,如下所示:
describe 'attempting to issue a direct POST request while not signed in' do
before { post users_path }
specify { expect(response).to redirect_to signin_path }
end
但是,尝试在 Posts 控制器上执行相同的测试在 before
块中失败:
describe 'attempting to issue a direct POST request while not signed in' do
before { post posts_path }
specify { expect(response).to redirect_to signin_path }
end
ArgumentError: wrong number of arguments (1 for 0)
包含patch post_path(post)
和delete post_path(post)
的等效测试功能并通过控制器中的before_action。
我的路线:
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
PATCH /posts/:id(.:format) posts#update
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
RSpec 是否被开机自检/开机自检混淆 - 即请求的名称与控制器的名称?
好吧,这确实是方法和模型名称之间的混淆,尽管我没有向上游看得足够远,无法看到它: 我的测试设置如下:
describe 'in the Posts controller' do
let(:post) { Post.create(...) }
.
.
.
describe 'attempting to issue a direct POST request while not signed in' do
before { post posts_path } # 'post' is interpreted to be the variable!
specify { expect(response).to redirect_to signin_path }
end
end
因此,HTTP 方法 POST 和在测试块开头声明的变量"post"之间存在命名冲突。将变量重命名为"test_post"修复了所有内容。
哎呀!
@DaveNewton:显然,在 POST 请求被完全拒绝的情况下,可以在没有参数的情况下对其进行测试。