Controll spec ActionController :: UrlGenerationError

时间:2016-08-22 16:35:57

标签: ruby-on-rails routes

我已经设置了路线,以便它们在我的控制器中按预期工作;我可以按预期使用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”动作,而不是像我期望的那样#c房间。

更新

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

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。

1 个答案:

答案 0 :(得分:0)

我不知道你在哪个版本的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拉入路径和网址助手。

我相信你没有默认的原因是rspec正在为不同类型的测试复制很多环境。对于控制器测试,它会拉动各种路径和网址助手,因为一般来说,他们经常使用它们经常值得吸引。例如,在模型测试中,它们不会在那里使用经常这样他们默认不会被拉进去。

这些帮助程序存在于app对象上。