1

この次の Controller テストは失敗しており、その理由がわかりません。

describe "GET 'index'" do 

    before(:each) do 
        @outings = FactoryGirl.create_list(:outing, 30)
        @user = FactoryGirl.create(:user)
    end 

    it "should be successful" do 
        get :index
        response.should be_success
    end 

end

Rspec は (あまり役に立たない) エラーを出します:

Failure/Error: response.should be_success
   expected success? to return true, got false

実際のコントローラーのコードも次のとおりです。

def index
    if @user
        @outings = Outing.where(:user_id => @user.id)
        @outing_invites = OutingGuest.where(:user_id => @user.id)
     else
        flash[:warning] = "You must log in to view your Outings!"
        redirect_to root_path
     end 
end

テストが失敗する原因を知っている人はいますか? Outing Controller の条件と関係があるのではないかと思いますが、パスするテストがどのようになるかはわかりません...

4

1 に答える 1

1

2つの別々のクラス間でインスタンス変数を混​​同しています。コントローラーは独自のクラスであり、仕様は独自のクラスです。彼らは状態を共有しません。この簡単な例を試して、理解を深めることができます...

def index
    // obvious bad code, but used to prove a point
    @user = User.first
    if @user
        @outings = Outing.where(:user_id => @user.id)
        @outing_invites = OutingGuest.where(:user_id => @user.id)
     else
        flash[:warning] = "You must log in to view your Outings!"
        redirect_to root_path
     end 
end

FactoryGirl.create_list(:outing, 30)外出を作成した後にユーザーを作成しているので、最初のユーザーを外出に関連付ける外出は作成されないので、あなたOuting.whereも失敗すると思います。

テストスタックにデータベースを含める場合、データベースにはテストが期待する方法でデータを含める必要があることを理解することが重要です。したがって、コントローラーが特定のユーザーに属する外出を照会している場合、仕様では、コントローラーが取得するユーザー(この場合、User.first私の例のひどい行)にも外出が関連付けられるように環境を設定する必要があります。仕様は期待しています。

于 2012-07-09T23:52:28.717 に答える