2012-08-26 98 views
1

我想測試從水豚的collection_select元素選擇一個值,由於某種原因,填充collection_select的數據不存在運行rspec時,但它是當運行rails應用程序。collection_select沒有填充rspec測試與水豚使用FactoryGirl

實施例:

HTML定義

<%= form_for(@notification) do |f| %> 

    <%= f.label :device, "Select a Device to notify:" %> 
    <%= f.collection_select :device_id, Device.all, :id, :device_guid, prompt: true %> 

<% end %> 

rspec的定義

describe "NotificationPages" do 

    subject { page } 

    let(:device) { FactoryGirl.create(:device) } 
    let(:notification) { FactoryGirl.create(:notification, device: device) } 

    describe "new notification" do 
    before { visit new_notification_path } 

    let(:submit) { "Create Notification" } 

    describe "with valid information" do 
     before do 
     select(device.device_guid, from: 'notification_device_id') 
     fill_in "Message", with: "I am notifying you." 
     end 

     it "should create a notification" do 
     expect { click_button submit }.to change(Notification, :count).by(1) 
     end 
    end 
    end 
end 

當運行測試時,得到以下錯誤消息:

Capybara::ElementNotFound: cannot select option, no option with text 'device_guid' in select box 'notification_device_id' 

看起來像collection_select中的Device.all調用在測試過程中沒有返回任何內容。任何關於我在做什麼的想法都是錯誤的?

感謝, 佩裏

回答

1

在您訪問new_notification_path沒有設備在數據庫中的那一刻。發生這種情況是因爲let是懶惰評估的,因此它定義的方法稱爲第一次調用它,在您的測試中,只有在執行select(device.device_guid ...)語句時纔會發生。

爲了確保設備在您訪問路徑之前創建,您可以在您之前的塊中調用「設備」。

before do 
    device 
    visit new_notification_path 
end 
+0

就是這樣。非常感謝你的解釋。 – Dowling

4

一種更好的方式來強制令的早期評估是使用,像這樣:

let!(:device) { FactoryGirl.create(:device) } 

這樣就不需要額外的代碼行。