rspec的行为与FactoryGirl一起使用

时间:2012-12-28 07:12:20

标签: rspec factory-bot

我正在尝试使用FactoryGirl为我的某个控制器规格创建一些项目:

摘录:

describe ItemsController do
    let(:item1){Factory(:item)}
    let(:item2){Factory(:item)}

    # This fails. @items is nil because Item.all returned nothing
    describe "GET index" do
        it "should assign all items to @items" do
            get :index
            assigns(:items).should include(item1, item2)
        end
    end

    # This passes and Item.all returns something 
    describe "GET show" do
        it "should assign the item with the given id to @item" do
            get :show, id => item1.id 
            assigns(:item).should == item1
        end
    end
end

当我将let更改为:

before(:each) do
    @item1 = Factory(:item)
    @item2 = Factory(:item)
end

我将@s放在变量前面,一切正常。为什么版本没有让我们工作?我尝试改变let让我们看到相同的行为。

1 个答案:

答案 0 :(得分:7)

let(:item1) { FactoryGirl.create(:item) }
let(:item2) { FactoryGirl.create(:item) }

实际上当你执行let(:item1)它会进行延迟加载时,在内存中创建对象但不将其保存在数据库中以及何时执行

@item1 = Factory(:item)

它将在数据库中创建对象。

试试这个:

describe ItemsController do
    let!(:item1){ Factory(:item) }
    let!(:item2){ Factory(:item) }

    describe "GET index" do
        it "should assign all items to @items" do
            get :index
            assigns(:items).should include(item1, item2)
        end
    end

    describe "GET show" do
        it "should assign the item with the given id to @item" do
            get :show, id => item1.id 
            assigns(:item).should == item1
        end
    end
end

如果不调用它,将永远不会被实例化,而在每次方法调用之前强制评估(:let!)。

或者你可以这样做:

describe ItemsController do
    let(:item1){ Factory(:item) }
    let(:item2){ Factory(:item) }

    describe "GET index" do
        it "should assign all items to @items" do
            item1, item2
            get :index
            assigns(:items).should include(item1, item2)
        end
    end

    describe "GET show" do
        it "should assign the item with the given id to @item" do
            get :show, id => item1.id 
            assigns(:item).should == item1
        end
    end
end