【问题标题】:Routes appear to exist in rake routes, unavailable when running spec路由似乎存在于 rake 路由中,运行规范时不可用
【发布时间】:2014-08-19 23:08:02
【问题描述】:

我似乎无法解决以下问题。

规格:(spec/api/power_ups_spec.rb)

describe Api::PowerUpsController, :type => :controller do
  describe "GET power_ups" do
    it "returns all power-ups" do
      FactoryGirl.create :power_up, name: "Increase rate of take", description: "You gain points more quickly"
      FactoryGirl.create :power_up, name: "Decrease rate of give", description: "You lose points more slowly"

      get api_power_ups_path, {}, { "Accept" => "application/json" }

      expect(response.status).to eq 200

      body = JSON.parse(response.body)
      power_up_names = body.map { |m| m["title"] }

      expect(power_up_names).to match_array(["Increase rate of take",
                                             "Decrease rate of give"])
    end
  end
end

路线:

Rails.application.routes.draw do
  namespace :api do
    resources :power_ups, only: [:index]
  end
end

控制器(app/controllers/api/power_up_controller.rb):

module Api
  class PowerUpsController < ApplicationController
    include ActionController::MimeResponds
    respond_to :json

    def index
      respond_with PowerUp.all
    end
  end
end

耙子路线:

     Prefix Verb URI Pattern              Controller#Action
api_power_ups GET  /api/power_ups(.:format) api/power_ups#index

运行规范的错误消息:

 Failure/Error: get api_power_ups_path, {}, { "Accept" => "application/json" }
     ActionController::UrlGenerationError:
       No route matches {:action=>"/api/power_ups", :controller=>"api/power_ups"}

【问题讨论】:

  • 换成get api_power_ups_path, :format =&gt; :json是否找到路由?
  • @infused,结果与错误信息No route matches {:action=&gt;"/api/power_ups", :controller=&gt;"api/power_ups", :format=&gt;:json}中添加format=>json的结果一样@
  • 我假设该路线在 RSpec 之外有效。有什么理由不在规范中使用get :index, :format =&gt; :json
  • @infused,谢谢你的工作。不是这样的唯一原因是我在教程中看到了它。

标签: ruby-on-rails rspec rails-routing


【解决方案1】:
get api_power_ups_path

这不是在控制器规范中使用 get 的方法。

在控制器规范中,您假设控制器中的被测类...所以您使用get 调用控制器上的实际方法。

在这种情况下,该方法称为index(即,您有def index),因此要激活您只需调用的测试:

get :index

仅当您引用其他路径时才使用路径助手 - 例如您被重定向到的位置等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-05
    • 1970-01-01
    • 2015-04-19
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    相关资源
    最近更新 更多