我正在使用rails教程并遇到错误。
$ bundle exec rspec spec
Failure/Error: expect { click_link "delete" }.should change(Micropost, :count).by(-1)
NoMethodError:
undefined method `destroy' for nil:NilClass
有两个错误,由nil的未定义方法'destory'的同一问题引起:NilClass
Micropost控制器
class MicropostsController < ApplicationController
before_filter :signed_in_user, only: [:create, :destory]
before_filter :correct_user, only: :destory
def create
@micropost = current_user.microposts.build(params[:micropost])
if @micropost.save
flash[:success] = "Micropost created!"
redirect_to root_path
else
@feed_items = []
render 'static_pages/home'
end
end
def destroy
@micropost.destroy
redirect_to root_path
end
private
def correct_user
@micropost = current_user.microposts.find_by_id(params[:id])
redirect_to root_path if @micropost.nil?
end
end
我认为这是帮助我弄清楚这个问题所需的所有信息。不管怎样,还有一些。
相关问题:Rails request spec not working - noMethodError
我尝试了他们的解决方案,但没有任何区别。
_feed_item.html.erb
<li id="<%= feed_item.id %>">
<%= link_to gravatar_for(feed_item.user), feed_item.user %>
<span class="user">
<%= link_to feed_item.user.name, feed_item.user %>
</span>
<span class="content"><%= feed_item.content %></span>
<span class="timestamp">
Posted <%= time_ago_in_words(feed_item.created_at) %> ago.
</span>
<% if current_user?(feed_item.user) %>
<%= link_to "delete", feed_item, method: :delete,
confirm: "You sure?",
title: feed_item.content %>
<% end %>
</li>
由于
答案 0 :(得分:4)
你有一个错字:
before_filter :correct_user, only: :destory
:destory
应为:destroy
,这会导致@micropost
为零。你在另一个before_filter btw。