【问题标题】:UrlGenerationError when running RSpec Test运行 RSpec 测试时出现 UrlGenerationError
【发布时间】:2023-03-31 05:55:01
【问题描述】:

我正在尝试运行一个测试,以确保我的show 模板是为餐厅呈现的。运行测试后,我得到:

 1) RestaurantsController GET #show 
     Failure/Error: before { get :show }
     ActionController::UrlGenerationError:
       No route matches {:action=>"show", :controller=>"restaurants"}

不知道为什么当确实有显示餐厅的路线时会这样说:

    restaurants GET    /restaurants(.:format)          restaurants#index
                POST   /restaurants(.:format)          restaurants#create
 new_restaurant GET    /restaurants/new(.:format)      restaurants#new
edit_restaurant GET    /restaurants/:id/edit(.:format) restaurants#edit
     restaurant GET    /restaurants/:id(.:format)      restaurants#show
                PATCH  /restaurants/:id(.:format)      restaurants#update
                PUT    /restaurants/:id(.:format)      restaurants#update
                DELETE /restaurants/:id(.:format)      restaurants#destroy

测试

require "rails_helper"

describe RestaurantsController do
  describe "GET #show" do
    before { get :show }

    it { should render_template("show") }
  end
end

【问题讨论】:

    标签: ruby-on-rails testing rspec controller shoulda


    【解决方案1】:

    你忘了id

    before { get :show, id: 1 } # Assuming there is a Restaurant with id=1
    

    【讨论】:

    • 哇,我很惊讶他们没有在应该的 Matcher 文档中包含这个(他们只提供get :show)。我是否需要为此创建一个工厂,因为此时我得到ActiveRecord::RecordNotFound: Couldn't find Restaurant
    • 是的!您可以通过Restaurant.create.id 来查看测试是否通过。但是使用工厂!
    猜你喜欢
    • 1970-01-01
    • 2020-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多