gpt4 book ai didi

ruby-on-rails - Controller RSpec : test PATCH update using custom ID

转载 作者:行者123 更新时间:2023-12-04 06:28:42 26 4
gpt4 key购买 nike

我在为 PATCH 更新编写 RSpec Controller 测试时面临挑战,因为路由和编辑使用我的模型生成的安全 edit_id,而不是标准的 1、2、3, Rails 自动生成的 4,5(序列号)。基本上,我不确定如何让我的测试使用此 edit_id 查找要编辑的请求。

我目前的测试:

describe "PATCH edit/update" do

before :each do
@testrequest = FactoryGirl.build(:request, name: "James Dong")
end

it "located the requested @testrequest" do
patch :update, id: @testrequest.edit_id, request: FactoryGirl.attributes_for(:request)
assigns(:request).should eq(@testrequest)
end

describe "using valid data" do

it "updates the request" do
patch :update, @testrequest.name = "Larry Johnson"
@testrequest.reload
@testrequest.name.should eq("Larry Johnson")
end
end

FactoryGirl 助手(我已经尝试过显式添加 edit_id 而不是 [即依赖模型创建 edit_id 本身],两者都没有区别)代码:

FactoryGirl.define do
factory :request do |f|
f.name { Faker::Name.name }
f.email { Faker::Internet.email }
f.item { "random item" }
f.detail { "random text" }
f.edit_id { "random" }
end
end

Controller :

def update
@request = Request.find_by_edit_id(params[:edit_id])
if @request.update_attributes(request_params)
flash[:success] = "Your request has been updated! We'll respond within one business day."
redirect_to edit_request_path(@request.edit_id)
else
render 'edit'
end
end

路由:

get 'edit/:edit_id', to: 'requests#edit', as: 'edit_request'
patch 'requests/:edit_id', to: 'requests#update', as: 'request'

最佳答案

好吧,有人帮我解决了这个问题,我觉得很傻。传递给 patch 方法的“id”可以是任何 id,所以我应该首先使用 edit_it 而不是尝试设置 id: edit_it。即,有效的代码:

before :each do
@testrequest = FactoryGirl.build(:request, name: "James Dong")
end

it "located the requested @testrequest" do
patch :update, edit_id: @testrequest.edit_id, request: FactoryGirl.attributes_for(:request)
assigns(:request).should eq(@testrequest)
end

describe "using valid data" do

it "updates the request" do
patch :update, edit_id: @testrequest.edit_id, request: FactoryGirl.attributes_for(:request, name: "Larry Johnson")
@testrequest.reload
@testrequest.name.should eq("Larry Johnson")
end
end

关于ruby-on-rails - Controller RSpec : test PATCH update using custom ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21297239/

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