0

有人可以告诉我为什么这很好用:

subject { page }
describe "for non-signed-in users" do
  describe "in the Microposts controller" do
    describe "submitting to the destroy action" do
      before { delete micropost_path(FactoryGirl.create(:micropost)) }
      specify { response.should redirect_to(signin_path) }
    end
  end
end 

但这会给出错误消息“nil:NilClass 的未定义方法‘destroy’”?:

subject { page }
describe "as wrong user" do
  let(:user) { FactoryGirl.create(:user) }
  let(:wrong_user) { FactoryGirl.create(:user, email: "wrong@example.com") }
  before { valid_signin user }
  describe "in the Microposts controller" do
    describe "submitting to the destroy action" do
      before { delete micropost_path(FactoryGirl.create(:micropost, user: wrong_user)) }
      specify { response.should redirect_to(root_path) }
    end
  end
end 

这是微博控制器:

class MicropostsController < ApplicationController
  before_filter :signed_in_user, only: [:create, :destroy]
  before_filter :correct_user,   only: :destroy

  def create
    @micropost = current_user.microposts.build(params[:micropost])
    if @micropost.save
      flash[:success] = "Micropost created!"
      redirect_to root_url
    else
      @feed_items = []
      render 'static_pages/home'
    end
  end

  def destroy
    @micropost.destroy
    redirect_to root_url
  end

  private

    def correct_user
      @micropost = current_user.microposts.find_by_id(params[:id])
    rescue
      redirect_to root_url # if @micropost.nil?
    end

end
4

1 回答 1

0

您期望第二个示例在correct_user. 我相当肯定没有引发异常,因此destroy在没有设置的情况下调用@micropost

您可以将find_by_id(不会引发异常)更改为(会引发异常find)。或者重写when @micropostis重定向的方法nil

于 2013-02-13T00:48:38.607 回答