gpt4 book ai didi

ruby-on-rails - 如何测试不存在的 Controller 操作?

转载 作者:行者123 更新时间:2023-12-04 04:44:49 25 4
gpt4 key购买 nike

ProductsController 中只有两个操作可访问:

# /config/routes.rb
RailsApp::Application.routes.draw do
resources :products, only: [:index, :show]
end

相应地设置测试:

# /spec/controllers/products_controller_spec.rb
require 'spec_helper'

describe ProductsController do

before do
@product = Product.gen
end

describe "GET index" do
it "renders the index template" do
get :index
expect(response.status).to eq(200)
expect(response).to render_template(:index)
end
end

describe "GET show" do
it "renders the show template" do
get :show, id: @product.id
expect(response.status).to eq(200)
expect(response).to render_template(:show)
end
end

end

你会如何测试另一个 CRUD actions不是 可访问?这在 future 可能会发生变化,因此测试将确保任何配置更改都会被注意到。
我找到了 be_routable matcher这看起来很有希望覆盖测试用例。

我推荐这个 post by Dave Newton which describes when and why to test controller actions .

最佳答案

这是我想出的:

context "as any user" do
describe "not routable actions" do
it "rejects routing for :new" do
expect(get: "/products/new").not_to be_routable
end
it "rejects routing for :create" do
expect(post: "/products").not_to be_routable
end
it "rejects routing for :edit" do
expect(get: "/products/#{@product.id}/edit").not_to be_routable
end
it "rejects routing for :update" do
expect(put: "/products/#{@product.id}").not_to be_routable
end
it "rejects routing for :destroy" do
expect(delete: "/products/#{@product.id}").not_to be_routable
end
end
end

然而,一项测试失败了:
Failure/Error: expect(get: "/products/new").not_to be_routable
expected {:get=>"/products/new"} not to be routable,
but it routes to {:action=>"show", :controller=>"products", :id=>"new"}

如果您采用完全不同的方法来测试不存在的路由,请随意添加您自己的解决方案。

关于ruby-on-rails - 如何测试不存在的 Controller 操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18357389/

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