ruby-on-rails - 测试在 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
解决方案
如果参数有效,您可以检查是否创建了帖子以及是否重定向了用户。如果您在 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
推荐阅读
- reactjs - 从material ui v1.0.0-beta升级
- sql - 使用触发器在 oracle db 中备份
- python-3.x - 如何在 Anaconda Python3 环境中为 python 安装 png 模块
- powerbi - 在 Power BI 中按站点计算(某些指标)患者的百分比
- python-3.x - 如何在 3D 中制作速度自相关函数 [python]
- python - 如何使用标准套接字对象初始化“MySocket”对象?
- python-3.x - 离散事件_随机数生成
- c - C中的自定义文件名
- android - 从基本模块调用动态功能代码
- python - 如何从python中的字符串解码十六进制值