2015-01-15 124 views
2

我有一個表單,當用戶提交一個單名字段的ajax表單,創建一個屬於一個模板對象的記錄。這一切都手動罰款,但由於某種原因,當我通過RSpec測試這告訴我,協會沒有創建。爲什麼這裏沒有更新模板對象?Rspec水豚測試Ajax調用不更新記錄

describe "edit page" do 
    before(:each) do 
    visit edit_admin_template_path(template) 
    end 

    context "form sections", js: true do 
    it "allows admin to create one" do 
     find("#btn-add-section").click 
     within('#new_form_section') do 
     fill_in 'Name', with: "Personal Info" 
     click_button "Create Section" 
     end 
     expect(template.form_sections.length).to eq(1) 
    end 
    end 
end 

這是我得到的失敗

Failure/Error: expect(template.form_sections.length).to eq(1) 

    expected: 1 
     got: 0 

    (compared using ==) 

UPDATE:只是注意到這個在RSpec的輸出

An error occurred in an after hook 
    ActionView::Template::Error: undefined method `form_sections' for nil:NilClass 

所以它告訴我,該模板對象不存在,那麼它能夠比較它呢?

更新2:所以看來,問題是等待在水豚完成ajax調用,在期待之前。我已將此添加到規範,它現在的作品,很明顯,我需要更好地refacotr這就像一個幫手

it "allows admin to create one" do 
    find("#btn-add-section").click 
    within('#new_form_section') do 
    fill_in 'Name', with: "Personal Info" 
    click_button "Create Section" 
    end 
    sleep(10) #this waits for the request to complete 
    expect(template.form_sections.length).to eq(1) 
end 

回答

2

的關鍵在於告訴RSpec的等待調用Ajax做任何預期之前完成。這是我用過的解決方案的一個很棒的帖子。

Thoughtbot - 自動等待AJAX​​ wioth水豚

http://robots.thoughtbot.com/automatically-wait-for-ajax-with-capybara「」

+0

這是我的想法,雖然。如果您有來自AJAX請求的'x'元素呈現,並且您有wait_for_ajax實現,該怎麼辦?這很好,但不完全冗長,是嗎?目前我們正在與功能測試進行爭執,這將會發布中斷,但是實際上找到中斷是什麼,因爲wait_for_ajax錯誤只是二進制的。你過去如何處理這個問題? – Schwad 2017-04-12 09:52:46

0

萬一別人絆倒在此,而不是使用睡眠,你可以基於UI本身測試。如果你使用have_css或找到匹配器,Capybara會等待這個元素重新加載,例如:

expect(page).to have_css(「#form-page-two」,visible::visible)#this將強制測試等待阿賈克斯呼叫

不得將Capybara.automatic_reload設置爲false。 (默認爲true)

該策略會減少測試套件的運行時間;如果測試只需要2或3秒來加載,它只會等待很長的時間(而不是10秒)。

但是,由於間歇性故障,寫入會令人沮喪。爲避免這種情況,您可能需要提高等待時間設置。

Capybara.default_max_wait_time = 10

https://github.com/teamcapybara/capybara#asynchronous-javascript-ajax-and-friends