我正在使用Cucumber,Capybara和RSpec。假设我在页面上列出了一些内容:
<ul>
<li><span class="title">Thing 1</span><span class="description">Desc 1</span></li>
<li><span class="title">Thing 2</span><span class="description">Desc 2</span></li>
<li><span class="title">Thing 3</span><span class="description">Desc 3</span></li>
</ul>
我可以通过以下方式获取所有这些列表项:
all('li').count.should == 3
现在我想测试每个项目的内容是否正确。订单很重要。我尝试了一些不同的东西,都感到非常混乱,或导致错误。例如:
things = Thing.all
all('li').each_with_index do |element, index|
within element do
page.should have_content things[index].title
page.should have_content things[index].description
end
end
undefined method `element' for #<Cucumber::Rails::World:0x007fe1b62f8308>
测试每个项目内容的最佳方法是什么?
答案 0 :(得分:4)
您可以将每个li的文本收集为数组:
all('li span.title').map(&:text)
然后您可以将该数组与预期内容进行比较。假设things
是可枚举的,您可以这样做:
things = Thing.all
expected_content = things.map(&title)
actual_content = all('li span.title').map(&:text)
# For an order dependent test:
expect(actual_content).to eq(expected_content)
# For an order independent test:
expect(actual_content).to match_array(expected_content)
鉴于需要检查多个部分,循环每个元素可能更容易,而不是重复上面的每个部分:
things = Thing.all
all('li').zip(things).each do |li, thing|
expect(li.find('span.title').text).to eq(thing.title)
expect(li.find('span.description').text).to eq(thing.description)
end