gpt4 book ai didi

ruby-on-rails - Rspec 在重定向后检查模板

转载 作者:数据小太阳 更新时间:2023-10-29 07:33:25 29 4
gpt4 key购买 nike

这是我为用户创建的操作:

def create
@user = User.new(user_params)

if @user.save
respond_to do |format|
format.html {
redirect_to edit_admin_user_path(@user)
flash[:success] = "Successfully created"
}
end
else
render :new
flash[:alert] = "Something went wrong"
end
end

我的测试是这样的:

context "POST methods" do

describe "#create" do
it "renders the edit template" do
post :create, user: FactoryGirl.attributes_for(:user)
expect(response).to render_template(:edit)
end
end
end

但是我收到了这个错误:

Failures:

1) Admin::UsersController POST methods #create renders the edit template
Failure/Error: expect(response).to render_template(:edit)
expecting <"edit"> but was a redirect to <http://test.host/admin/users/80/edit>

我想检查创建用户后是否呈现 edit.html.haml 文件。我做错了什么?

更新#1我确实在另一个测试中检查了重定向,这是我的完整测试套件:

require 'rails_helper'

RSpec.describe Admin::UsersController, type: :controller do

render_views

context "POST methods" do

describe "#create" do
it "using valid params" do

expect{
post :create, user: { email: "something@hello.com", password: "long12345678" }
}.to change(User, :count).by(1)
# get user_path('1')
end

it "redirects to the edit page after saving" do
post :create, user: FactoryGirl.attributes_for(:user)
user = User.last
expect(response).to redirect_to(edit_admin_user_path(user.id))
end

it "renders the edit template" do
post :create, user: FactoryGirl.attributes_for(:user)
user = User.last
expect {
redirect_to(edit_admin_user_path(user.id))
}.to render_template(:edit)
end

context "it redirects to new" do
it "if user has no valid mail" do
post :create, user: { email: "something", password: "long12345678" }
expect(response).to render_template(:new)
end
it "if user has no valid password" do
post :create, user: { email: "something@mail.com", password: "short" }
expect(response).to render_template(:new)
end
end
end
end
end

我想要的是实际检查编辑模板是否已呈现。因为 expect(response).to redirect_to(edit_admin_user_path(user)) 它不会检查模板。即使我根本没有 edit.html.haml 文件,这个测试也会通过。

最佳答案

当您测试create 操作时,您应该只检查重定向的正确性。在此操作中,您实际上并未呈现 edit 模板,而只是重定向到已创建实体的 edit 路径。所以这是你应该检查的东西。

describe "#create" do
it "redirects to the edit path" do
post :create, user: FactoryGirl.attributes_for(:user)
expect(response).to redirect_to(edit_admin_user_path(User.last))
end
end

然后您应该对 edit 操作进行另一个测试,您将在其中检查模板呈现。这意味着在创建操作中重定向后,您还将看到正确的模板。

关于ruby-on-rails - Rspec 在重定向后检查模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42232583/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com