在RSpec中测试Rails视图:为什么它会路由到" show"当我想测试"索引"?

时间:2015-06-03 14:35:28

标签: ruby-on-rails view rspec

我在spec/views/users/index_spec.rb中有这个非常基本的视图规范:

require 'rails_helper'

RSpec.describe "users/index", type: :view do
  before(:each) do
    @user = create(:user)
    assign(:users, [@user])
  end

  it "renders a list of users" do
    render
    expect(page).to have_selector "tr##{dom_id(@user)}"
  end
end

执行时,它会告诉我以下内容:

Failures:

  1) users/index renders a list of users
     Failure/Error: render
     ActionView::Template::Error:
       No route matches {:action=>"show", :controller=>"users", :id=>nil, :locale=>#<User id: 1, name: "Rosalinda Dach", email: "marilie@leffler.ca", encrypted_password: "$2a$04$G/z6lbFUpnh9FD3bymYBE.LrJK3acKr4TsURgCq7B77...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, confirmation_token: nil, confirmed_at: "2015-06-03 14:33:11", confirmation_sent_at: nil, unconfirmed_email: nil, failed_attempts: 0, unlock_token: nil, locked_at: nil, created_at: "2015-06-03 14:33:12", updated_at: "2015-06-03 14:33:12", avatar: nil>} missing required keys: [:id]
     # /Users/josh/.rvm/gems/ruby-2.1.0@a4aa2/gems/actionpack-4.2.1/lib/action_dispatch/journey/formatter.rb:46:in `generate'
     # /Users/josh/.rvm/gems/ruby-2.1.0@a4aa2/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:727:in `generate'
     # /Users/josh/.rvm/gems/ruby-2.1.0@a4aa2/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:758:in `generate'
     # /Users/josh/.rvm/gems/ruby-2.1.0@a4aa2/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:801:in `url_for'
     # /Users/josh/.rvm/gems/ruby-2.1.0@a4aa2/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:280:in `call'
     # /Users/josh/.rvm/gems/ruby-2.1.0@a4aa2/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:345:in `block (2 levels) in define_url_helper'

为什么测试路由到users#show而不是users#index

2 个答案:

答案 0 :(得分:0)

您可以更改代码:

RSpec.describe "users/index.html.erb", type: :view do

答案 1 :(得分:0)

由于我没有找到合适的解决方案,我决定创建我自己的在线Markdown编辑器,复制并粘贴:PIMP( P asteable I mages, M arkdown, P andoc)。

http://pimp.suhail.uberspace.de/en

它还没有看起来很棒,但它提供了使用Pandoc非常强大的Markdown创建语义上令人敬畏的文档所需的一切,将图像直接从剪贴板粘贴到文本中,并将文档导出到各种格式(当时是Docx,Epub,Odt,后来也可能是PDF)。

目前,要使用PIMP,必须创建一个用户帐户。

整个项目相当于概念验证,而不是真正的项目,但如果人们喜欢并使用它,我很乐意将其作为一个真正的项目。