测试在RSpec中重定向的请求

问题描述 投票:0回答:2

我正在尝试测试一个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
ruby-on-rails rspec
2个回答
0
投票

如果params有效,您可以检查是否创建了帖子并且用户是否被重定向。如果你在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

-1
投票

自成功创建帖子以来,您的响应代码将为302。在您给出的示例代码中,您将无法获得201。您可以检查您是否收到201

expect(response).to_not have_http_status(201).

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

© www.soinside.com 2019 - 2024. All rights reserved.