2012-12-28 19 views
0

我試圖用FactoryGirl爲我控制器的規格之一創建幾個項目:行爲的RSpec的讓與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 

當我改變讓這個:

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

我把@放在變量的前面,一切正常。爲什麼不讓版本讓我們工作?我試着改變讓讓!並看到相同的行爲。

回答

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

其實,當你讓(:項目1)它會做延遲加載,在內存中創建對象而不是將其保存在數據庫中,當你做

@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 

讓利將永遠不會被實例化。

,或者你可以這樣做:

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 
+0

可以接受的答案,如果它有回答這個問題 –

+0

您好,感謝您的建議。這並沒有解決問題。最後,我的問題說,我已經試過了。 – mushroom

相關問題