2017-02-26 104 views
1

我得到的RSpec +水豚+吵鬧鬼以下錯誤:水豚迫不及待Ajax請求

given!(:user_owner) { create(:user) } 
given!(:second_user) { create(:user) } 
given!(:question) { create(:question, user: user_owner) } 

describe 'as not question owner' do 
    before do 
    login_as(second_user, scope: :user, run_callbacks: false) 
    visit question_path(question) 
    end 

    scenario 'can upvote just one time', js: true do 
    first('a#question-upvote').click 
    expect(first('div#question-score').text).to eq '1' 
    first('a#question-upvote').click 
    expect(first('div#question-score').text).to eq '1' 
    end 

故障/錯誤:期待(page.first( '#DIV問題 - 得分')文本。)。爲了EQ '-1'

expected: "-1" 
     got: "0" 

當我插入睡眠1:

scenario 'can upvote just one time', js: true do 
    first('a#question-upvote').click 
    sleep 1 
    expect(first('div#question-score').text).to eq '1' 
    first('a#question-upvote').click 
    sleep 1 
    expect(first('div#question-score').text).to eq '1' 
end 

試驗合格。

我明白了頁面沒有異步請求。 如何重寫測試以使其在沒有睡眠的情況下正常工作?

P.S.對不起英文。

回答

3

通過使用eq匹配器,您正在查殺任何等待的行爲。這是因爲一旦你在一個找到的元素上調用.text你有一個字符串,並且在與eq匹配器一起使用時無法重新加載/重新查詢該字符串。如果你想等待/重試行爲,你需要使用水豚提供的水豚與水豚元素。

所以不是expect(first('div#question-score').text).to eq '1'你應該做

expect(first('div#question-score')).to have_text('1', exact: true) # you could also use a Regexp instead of specifying exact: true 

另外一點需要注意的是,all/first元素禁止重載,因此,如果整個頁面被改變(或元素,你是在等待文本被完全替換),並且初始頁面有一個與選擇器相匹配的元素,但實際上您希望檢查第二個頁面(或替換的元素)中的元素,因此您不應該使用first/all - 在這種情況下,您會想用find查詢使用css:first-child /:first-of-type等typ e事物(或等價的XPath)來唯一標識元素,而不是返回多個元素並挑選其中的一個。如果它只是在頁面上異步替換元素的值,那麼您不必擔心它。

+0

謝謝Thomas。你再次幫助我。 –