【问题标题】:spec for nested routes嵌套路由规范
【发布时间】:2016-09-28 10:53:28
【问题描述】:

我的路线是:

resources :posts
  resources :images
end

我想为 ImagesController 编写规范:

it "renders the index template" do
  get :index, {:id => @post.id}
  expect(response).to render_template("index")
end

错误是

No route matches {:action=>"index", :controller=>"images", :id=>"19"}

我该如何解决这个问题?

编辑:

post_id 修复,但似乎仍然没有得到参数:

新的错误是

Failure/Error: get :index, {post_id: @post.id}
     NoMethodError: undefined method `+' for nil:NilClass

索引视图:

  def index
    @post = Post.find(params[:post_id])
    @calculations = @post.something + 1
  end

【问题讨论】:

  • get :index, :post_id => @post.id
  • @AndreyDeineko Failure/Error: get :index, {:post_id => @post.id} NoMethodError: undefined method +' for nil:NilClass` 我当然定义了@post
  • 你认为我可以帮你做最新的吗?至少它不再说没有路线,所以它解决了问题
  • 我可以添加它作为答案,你可以接受它然后再问一个新的,除非你自己明白哪里出了问题
  • 您无法即时更改您的问题。最初你收到No route match 错误,我帮你解决了。这是另一个问题,因为它暴露了不同的问题。

标签: ruby-on-rails ruby-on-rails-4 routing routes


【解决方案1】:

您应该传递post_id 参数:

get :index, post_id: @post.id

编辑

在您使用我们可以看到的正确信息更新问题后,您的代码存在一些问题:

@post = Post.find(params[:post_id]) # should be Post.find(params[:id])
@calculations = @post.something + 1 # thus this is `nil` + 1 - error

【讨论】:

  • 实际上params[:post_id] 很好,因为它更加嵌套。感谢您对第一个错误的帮助,其余的自己调试!
  • @J.Doe 从您的问题中不知道 resources :posts 也是嵌套的。但是很好,你找到了它
猜你喜欢
  • 2014-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-30
  • 2011-11-07
  • 2020-07-18
相关资源
最近更新 更多