【问题标题】:Controll spec ActionController::UrlGenerationError控制器 rspec ActionController::UrlGenerationError
【发布时间】:2016-12-29 07:16:47
【问题描述】:

我已经设置好路由,以便它们在我的控制器中按预期工作;我可以按预期使用 room_path 和 rooms_path。

但是,当我出于某种原因尝试在控制器规范中使用相同的路由时,会出现错误:

ActionController::UrlGenerationError: 没有路线匹配 {:action=>"/1", :controller=>"rooms"}

我的 routes.rb 文件:

  root "rooms#index"
  resources :rooms, :path => '/', only: [:index, :create, :show] do 
    resources :connections, only: [:create,:destroy]
  end

如果我耙路线:

room_connections POST   /:room_id/connections(.:format)     connections#create
room_connection DELETE  /:room_id/connections/:id(.:format) connections#destroy
rooms GET    /              rooms#index
      POST   /              rooms#create
room  GET    /:id(.:format) rooms#show

但是我的测试失败了:

describe "GET room_path(room)" do
    it "renders show" do
      @room = Room.create
      get room_path(@room)
      expect(response.status).to eq(200)
      expect(response).to render_template(:show)
    end
end

虽然我的控制器可以毫无问题地使用相同的路由助手:

class RoomsController < ApplicationController
  def index
  end

  def create
    @room = Room.create
    redirect_to room_path(@room)
  end

  def show
    @room = Room.find(params[:id])
  end
end

我不确定为什么在我的测试中它似乎在寻找“/1”动作而不是像我期望的那样寻找房间#show。

更新

所以继续玩这个我已经能够通过更改以下内容获得测试绿色:

describe "GET room_path(room)" do
    it "renders show" do
      @room = Room.create
      get :show, params: { id: @room.id }
      expect(response.status).to eq(200)
      expect(response).to render_template(:show)
    end
 end

我仍然很想了解为什么我的助手不起作用。这是可以预料的吗?手动编写参数哈希是一种 PITA。

【问题讨论】:

    标签: ruby-on-rails routes


    【解决方案1】:

    我不知道您使用的是哪个版本的 Rails 和 RSpec。这适用于 Rails 4.2 和 Rspec 3.4.4:

    describe "my neat test description", type: :routing do
      it "can use path helper" do
        puts whatever_path
      end
    end
    

    type: :routing 引入路径和 url 助手。

    我相信默认情况下您没有该功能的原因是 rspec 正在为不同类型的测试复制大量环境。对于控制器测试,它引入了各种路径和 url 助手,因为一般来说,它们在那里经常被使用,值得引入。例如,在模型测试中,它们不经常在那里使用,所以它们不会被引入默认情况下。

    这些助手存在于 app 对象上。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-25
      相关资源
      最近更新 更多