2017-02-26 99 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。你再次帮助我。 –