【问题标题】:Behavior of rspec let with FactoryGirlrspec let 与 FactoryGirl 的行为
【发布时间】:2012-12-28 07:12:20
【问题描述】:

我正在尝试使用 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 更改为 let!s 并看到相同的行为。

【问题讨论】:

    标签: rspec factory-bot


    【解决方案1】:
    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 永远不会被实例化,而 (: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
    

    【讨论】:

    • 您好,感谢您的建议。这并没有解决问题。最后我的问题说我已经尝试过了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多