2011-12-26 68 views
0

我不明白爲什麼這個RSpec測試失敗。有什麼建議?
我嘗試處理帖子的銷燬。只有創建帖子的用戶才能刪除它們。Ruby的問題與過濾器和RSpec

class PostsController < ApplicationController 
    before_filter :authorized_user, :only => :destroy 

def destroy 
    post = Post.find(params[:id]) 
    post.destroy 
    redirect_to posts_path, notice: 'Post successfully destroyed' 
end 

private 
def authorized_user 
    redirect_to posts_path, notice: 'Access Denied' if current_user.posts.find_by_id(params[:id]).nil? 
end 

測試:

describe "DELETE destroy" do 
before(:each) do 
    @post = stub_model(Post, :id => 23) 
    @post.stub(:destroy){true} 
    Post.stub(:find){@post} 
end 
it "should search the post" do 
    Post.should_receive(:find).with(@post.id.to_s).and_return(@post) 
    delete :destroy, {:id => @post.id } 
end 

it "should destroy the post" do 
    @post.should_receive(:destroy) 
    delete :destroy, {:id => @post.id } 
end 
it "should redirect to the posts list" do 
    delete :destroy, {:id => @post.id } 
    response.should redirect_to posts_path 
end 
end 

和錯誤:

1) PostsController DELETE destroy should search the post 
Failure/Error: Post.should_receive(:find).with(@post.id.to_s).and_return(@post) 
    (<Post(id: integer, title: string, body: text, created_at: datetime, updated_at: datetime, user_id: integer) (class)>).find("23") 
     expected: 1 time 
     received: 0 times 
# ./spec/controllers/posts_controller_spec.rb:67:in `block (3 levels) in <top (required)>' 

回答

0

我認爲這是因爲前(:每個)塊,你必須登錄的用戶。你有before_filter,這個過濾器只適用於:destroy。所以當你沒有登錄用戶時,你的測試會失敗,因爲它實際上是一個沒有「運行測試」權限的用戶。所以,你應該把這個代碼前(:每個):

user = way_to_make_user - I do it with: FactoryGirl.create(:user,role=>"client") 
controller.sign_in user 

如果你告訴我,你用什麼身份驗證,我可以幫你。我使用康康寶石。所以重點是你必須在每次測試之前登錄用戶。