【问题标题】:RSpec view test ActionView::Template::Error: No route matches {:action=>RSpec 视图测试 ActionView::Template::Error: No route matches {:action=>
【发布时间】:2013-10-11 00:40:19
【问题描述】:

我正在尝试让我的 RSpec 视图测试通过并收到上述错误。通过搜索,我认为这是嵌套路由的问题,但我无法弄清楚如何解决它。这是完整的错误:

programs/show
  renders attributes in <p> (FAILED - 1)

Failures:

  1) programs/show renders attributes in <p>
     Failure/Error: render
     ActionView::Template::Error:
       No route matches {:action=>"sort_cycles", :controller=>"programs", :id=>nil}

它在代码中抱怨的那一行是:

<ul class="cycles" data-update-url="<%= sort_cycles_program_url(params[:id]) %>" >

测试看起来像:

require 'spec_helper'

describe "programs/show" do
  before(:each) do
    FactoryGirl.create(:goal)
    FactoryGirl.create(:experience_level)
    @program = FactoryGirl.create(:program)
  end

  it "renders attributes in <p>" do
    render
    rendered.should match(/Name/)
    rendered.should match(/Gender/)
    rendered.should match(Goal.find(@program.goal_id).name)
    rendered.should match(ExperienceLevel.find(@program.experience_id).name)
  end
end

路线看起来像这样:

resources :programs do
    member { post :sort_cycles }
    resources :cycles_programs do
    end
  end

ProgramsController 中的 sort_cycles 操作

def sort_cycles
    params[:cycles_program].each_with_index do |cycle_program_id, index|
      cycle_program = CyclesProgram.find(cycle_program_id)
      cycle_program.cycle_order = index+1
      cycle_program.save
    end
    render nothing: true
  end

编辑:

这是视图中的完整代码块:

<ul class="cycles" data-update-url="<%= sort_cycles_program_url(params[:id]) %>" >
  <% @program.cycles_programs.each do |program| %>
    <%= content_tag_for :li, program, class: "cycle-block" do %>
      <%= link_to program.cycle.name, program.cycle %> | <%= link_to "Remove", program_cycles_program_path(@program, program), method: :delete %>
    <% end %>
  <% end %>
</ul>

【问题讨论】:

  • rake routes 向您显示sort_cycles 路径的什么?

标签: ruby-on-rails rspec


【解决方案1】:

按照您编写的方式,sort_cycles_program_url(params[:id]) 将路由到 ProgramsController 内的 sort_cycles 操作。这里可能有很多事情失败了,所以请确保它们都正确:

  1. ProgramsController 中定义了sort_cycles 操作
  2. views/programs 中有一个sort_cycles.html.erb 模板,除非您要呈现不同的模板(不清楚您上面的HTML 代码的放置位置)
  3. 确保您的 sort_cycles 操作可以处理 params[:id] == nil,因为这就是您提供的内容

【讨论】:

  • 回答你的第一个问题,rake routes for sort_cycles 给出sort_cycles_program POST /programs/:id/sort_cycles(.:format) programs#sort_cycles
  • ProgramsController 中定义了一个sort_cycles 操作,我用该代码更新了问题。而且,sort_cycles 用于允许用户使用 jquery .sortable 拖动和重新排序“循环”列表并将新订单保存到数据库中。该功能确实有效。
  • 嗯,可以试试sort_cycles_program_path吗?
  • “确保您的sort_cycles 操作可以处理params[:id] == nil?”是什么意思,这可能是导致测试失败的原因吗?我还用导致测试失败的完整代码块再次更新了问题。
  • “嗯,也许试试 sort_cycles_program_path 代替?”在哪里?
猜你喜欢
  • 2015-04-15
  • 1970-01-01
  • 2022-12-26
  • 2017-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-26
  • 1970-01-01
相关资源
最近更新 更多