如何测试不存在的控制器操作? [英] How to test a controller action that does not exist?

查看:43
本文介绍了如何测试不存在的控制器操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

There are only two actions accessible in the 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 操作无法访问吗?这可能会在未来发生变化,因此测试将确保会注意到任何配置更改.
我找到了 be_routable 匹配器 看起来很有希望覆盖测试用例.

How would you test that the other CRUD actions are not accessible? This might change in the future so the tests will ensure any configuration change will be noticed.
I found the be_routable matcher which looks promising to cover the test case.

我推荐这篇Dave Newton 的帖子,其中描述了何时以及为什么要测试控制器动作.

推荐答案

这是我的想法:

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"}

<小时>

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


Please feel free to add your own solution if you follow a totally different approach to test non-existing routes.

这篇关于如何测试不存在的控制器操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆