2011-12-26 12 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 

あなたは認証のために何を使うかを教えている場合、私はより多くのあなたを助けることができます。私はカンカンの宝石を使用します。だから、主なポイントは、各テストの前にユーザーにログインする必要があるということです。