【问题标题】:Testing requests that have redirects in RSpec测试在 RSpec 中有重定向的请求
【发布时间】: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


【解决方案1】:

如果参数有效,您可以检查帖子是否已创建以及用户是否已重定向。如果您在 Post 模型中有任何验证,最好测试无效参数:

RSpec.describe 'PostsController', type: :request do
  describe 'POST #create' do
    context 'with valid params' do
      it 'creates a new post' do
        expect { post posts_path, params: { post: valid_attributes } }.to change(Post, :count).by(1)        
        expect(response).to redirect_to post_path(Post.last)
      end
    end

    context 'with invalid params' do
      it 'does not create a new post' do
        expect { post posts_path, params: { post: invalid_attributes } }.not_to change(Post, :count)
        expect(response).to have_http_status 200
      end
    end
  end
end

【讨论】:

    【解决方案2】:

    由于帖子创建成功,您的响应代码将是 302。在您获得的示例代码中,您不会得到 201 回复。你可以检查一下你没有收到 201

    expect(response).to_not have_http_status(201).
    

    创建新的 Post 模型不会返回 HTTP 状态代码。它在数据库中创建一行。如果您想检查帖子是否已创建,您可以检查帖子数在测试开始时为 0,在测试结束时为 1。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-23
      • 1970-01-01
      • 2011-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多