【发布时间】:2019-01-17 23:58:18
【问题描述】:
我正在尝试测试一个 post 请求,如果成功则有重定向:
class PostsController < ApplicationController
def create
@post = Post.new(post_params)
if @post.save
redirect_to @post, notice: 'Post was successfully created.'
else
render :new
end
end
end
我想知道是否有可能测试我是否在重定向之前收到 201 响应代码。这是我目前拥有我的代码的方式。它会出错,因为重定向首先发生:
RSpec.describe 'Posts', type: :request do
describe 'POST #create' do
it 'has a 201 response code' do
post posts_path, params: { post: valid_attributes }
expect(response).to have_http_status(201)
end
end
end
【问题讨论】:
-
由于帖子创建成功,您的响应代码为 302。在您获得的示例代码中,您不会得到 201 回复。您可以检查您是否没有收到 201:expect(response).to_not have_http_status(201)。
-
所以尽管创建了新记录,但我会得到 302,因为我在控制器中明确写了它?这种情况下没有执行顺序?
-
创建新的 Post 模型不会返回 HTTP 状态代码。它在数据库中创建一行。如果您想检查帖子是否已创建,您可以检查帖子数在测试开始时为 0,在测试结束时为 1。
-
啊,明白了。谢谢。随意张贴作为答案。
标签: ruby-on-rails rspec