有人可以告诉我为什么这样可行:
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的错误信息“undefined method`troy'”?:
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
答案 0 :(得分:0)
您希望第二个示例在correct_user
的救援区域内重定向。我非常确定没有引发任何异常,因此在未设置destroy
的情况下调用@micropost
。
您可以将find_by_id
(不会引发异常)更改为find
(确实如此)。或者在@micropost
为nil
时重写方法以重定向。