1

以下控制器测试失败,我不知道为什么:

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

您在两个单独的类之间混淆了实例变量 - 控制器是它自己的类,而规范是它自己的类。他们不共享状态。你可以试试这个简单的例子来更好地理解......

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也会失败。

Its important to understand that when you are including the database in your test stack the database needs to contain the data in the way the test expects. So if your controller is querying for outings belonging to a specific user your spec needs to setup the environment such that the user the controller will retrieve (in this case, the terrible line with User.first from my example) will also have the outings associated with it that the specification is expecting.

于 2012-07-09T23:52:28.717 回答