2013-05-30 68 views
0

我想通過將在每個示例中實例化的東西放入基於文檔的let方法來清除一些規格:https://www.relishapp.com/rspec/rspec-core/v/2-13/docs/helper-methods/let-and-let!第二個規範中的ObjectConnection部分是作爲main_menu的一部分創建的。如果我通過rails控制檯執行它,它工作正常。使用let和factorygirl兩個例子 - 不知道爲什麼這不起作用

describe "shall comment on items" do 

    let(:menu) { FactoryGirl.create(:main_menu) } # i am assuming that I have access to a menu variable 

    # this one works 
    it 'should submit a message to a valid location' do 
    kt=menu.location 
    xhr :post, :create_message, {content: "here is my content", associated_global_id: kt.global_id } 
    response.code.should == "200" 
    end 

    # this one doesn't 
    it 'should submit a message to a valid object connection' do 
    pairing=ObjectConnection.first # multiple ObjectConnections are created as part of the main_menu factory 
    xhr :post, :create_message, {content: "here is my approval of your pairing seneor", associated_global_id: pairing.global_id } # this is where the error is 
    response.code.should == "200" 
    end 
end 

當我跑,我得到:

undefined method `global_id' for nil:NilClass 

在第二個例子中

這是應如何工作的?或者我需要在每個示例中聲明menu = FactoryGirl.create(:main_menu)?

回答

2

如果要測試對象的實例化的副作用,請使用let!

經常加載的是let

+0

啊......這就是我想要記住的。這也做了兩套插入,這不正是我正在尋找的,但它肯定解決了這個問題。謝謝 – timpone

1

僅在引用變量時調用let語句塊。由於它在第二個例子中沒有被引用,所以沒有被調用。你應該能夠只是在這個例子的頂部像

x = menu 

添加的東西來獲取所謂的let塊。

由於像這樣的混淆,這可能是一種反模式,因爲它的副作用使用了let聲明。

+0

ahh,thx森。現在,我正在寫這個數據庫。那麼這個例子會爲每個例子做插入操作,而不僅僅是兩個例子的插入操作? – timpone

+0

@timpone,我不知道,但你可以測試一下。 – Mori

+0

thx森,它做兩套插入。嗯...不完全是我期待的行爲,但我想它使代碼更易讀,儘管不完全確定。 – timpone

相關問題