Rspec Rails请求规范不起作用-命名错误

Rspec Rails请求规范不起作用-命名错误,rspec,railstutorial.org,Rspec,Railstutorial.org,有人能告诉我为什么这样做很好: 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)) } specif

有人能告诉我为什么这样做很好:

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'”:

这是microposts控制器:

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
class MicropostsController
您希望第二个示例在
correct\u user
的rescue块中重定向。我相当确定没有引发异常,因此在未设置
@micropost
的情况下调用
destroy

您可以将
find\u by\u id
(不会引发异常)更改为
find
(会引发异常)。或者在
@micropost
nil
时重写重定向方法

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