首页 > 解决方案 > 测试在 RSpec 中有重定向的请求

问题描述

如果成功,我正在尝试测试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-railsrspec

解决方案


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

推荐阅读