ruby-on-rails - rspec 期待空路由

标签 ruby-on-rails ruby rspec

我正在我的应用程序上实现一个 API,并使用 Rspec 对其进行测试。

我的项目 Controller 没有 newedit 操作,并且 routes.rb 没有它们的路线:

namespace :api, defaults: {format: 'json'} do
  namespace :v1 do
    resources :items, except: [:new, :edit]
  end
end

我对它们的 rspec 测试如下:

it "raises error on #new" do      
  expect(:get => "/api/v1/items/new").to have_http_status(404)
end

但是当我对其执行测试时,我得到:

Api::V1::ItemsController routing raises error on #new
 Failure/Error: expect(:get => "/api/v1/items/new").to have_http_status(404)
   expected a response object, but an instance of Hash was received
 # ./spec/routing/items_routing_spec.rb:11:in `block (3 levels) in <top (required)>'

我不确定如何处理这种情况并让测试通过。

最佳答案

您可能正在寻找 be_routable匹配器:

it { expect(get: '/api/v1/items/new').to_not be_routable }

来自文档:

The be_routable matcher is best used with should_not to specify that a given route should not be routable. It is available in routing specs (in spec/routing) and controller specs (in spec/controllers).

作为解决 new 被解释为 show 问题的解决方法,您可以使用名为 route_to 的替代匹配器:

it { expect(get: '/api/v1/items/new').to_not route_to('/api/v1/items#new') }

it { expect(get: '/api/v1/items/new').to_not route_to(controller: '/api/v1/items', action: 'new') }

关于ruby-on-rails - rspec 期待空路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27945543/

相关文章:

ruby-on-rails - header 部分中的ransack搜索表单:没有将Ransack::Search对象提供给search_form_for

ruby-on-rails - Belongs_to 和 where 条件

ruby - 如何获取子字符串在文本中出现的次数

ruby-on-rails - 使用 Turbolinks 和 jQuery Turbolinks

ruby - Rspec any_instance stub 导致错误未定义方法 __rspec_original_dup

ruby-on-rails - 比较两个具有未知值的哈希值

javascript - 有哪些代码质量/代码覆盖率工具可用于检查 Jasmine 中的 Javascript 测试?

mysql - 如何阻止 Rails 转义 SQL 中特定列的值?

ruby - Rspec Controller 中显示的#<RSpec::Core::ExampleGroup::Nested_1 的未定义方法 `get'

ruby-on-rails - capybara NoMethodError : undefined method `visit' for