【问题标题】:Testing view that uses will_paginate with RSpec gives "No route matches"将 will_paginate 与 RSpec 一起使用的测试视图给出“无路由匹配”
【发布时间】:2014-01-22 16:13:10
【问题描述】:

我正在尝试测试使用 will_paginate 的视图,但我收到了无法解释的 No route matches 错误。请注意,通过浏览器或控制器/功能规范访问stations/1/measures/page/2 是有效的。

routes.rb

  ...

  resources :stations, shallow: true do
    resources :measures, only: [:show, :create, :destroy]
  end
  get "/stations/:station_id/measures/page/:page", to: "stations#measures", as: :station_measures_paginate

  ...

views/stations/measures.erb.html

    <div class="row">
      <h1>Latest measures for <%= @station.name.capitalize %></h1>
      <p>Latest measurement recieved at <%= time_date_hours_seconds(@measures.last.created_at) %></p>
      <%= render :partial => 'measures/table', object: @measures %>

      <%= will_paginate @measures %>
    </div>

这些规格:

spec/views/stations/measures.html.erb_spec.rb

    require 'spec_helper'

    describe "stations/measures" do

      let!(:station) { build_stubbed(:station) }

      let!(:measures) do
        [*1..30].map! { build_stubbed(:measure, station: station) }.paginate
      end

      before(:each) do
        Measure.stub(:last).and_return(measures.last) 
        assign(:station, station)
        assign(:measures, measures)
        stub_user_for_view_test
      end

      subject {
        render
        rendered
      }

      it { should match /Latest measures for #{station.name.capitalize}/ }
      it { should match /Latest measurement recieved at #{measures.last.created_at.strftime("%H:%M")}/ }
      it { should have_selector '.pagination' }

    end

给出以下错误三遍:

  1) stations/measures 
     Failure/Error: render
     ActionView::Template::Error:
       No route matches {:page=>2, :controller=>"stations", :action=>"measures"}
     # ./app/views/stations/measures.html.erb:6:in `_app_views_stations_measures_html_erb___1173544536802428572_70225207801140'
     # ./spec/views/stations/measures.html.erb_spec.rb:23:in `block (2 levels) in <top (required)>'
     # ./spec/views/stations/measures.html.erb_spec.rb:27:in `block (2 levels) in <top (required)>'
     # -e:1:in `<main>'


    ...

【问题讨论】:

标签: ruby-on-rails rspec ruby-on-rails-4 rspec2 will-paginate


【解决方案1】:

原因是您需要使用您在 routes.rb 中定义的 station_id 来提供路由。有问题显示的参数中没有这样的东西。

我从未在 Rspec-rails 中编写过视图测试,也不知道如何适应这条路线。我建议您改用控制器测试,添加render_views 宏以允许渲染视图,然后可以访问response.body

由于分页逻辑主要是在控制器中实现的,我认为在控制器中分类这个测试是完全合理的。

【讨论】:

  • 我有一个控制器规范,它测试它是否对@measures 资源进行了分页。我知道有些人不使用视图测试,但我发现存根数据库并专注于视图测试中的视图逻辑要容易得多。
  • @papirtiger,我同意视图测试在需要时是完全可以接受的。但似乎很难为这个视图测试设置正确的路线。
猜你喜欢
  • 1970-01-01
  • 2018-08-24
  • 1970-01-01
  • 2018-02-11
  • 1970-01-01
  • 2014-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多