我正在使用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>
Run Code Online (Sandbox Code Playgroud)
我可以通过以下方式获得所有这些列表项:
all('li').count.should == 3
Run Code Online (Sandbox Code Playgroud)
现在,我要测试每个项目的内容是否正确。顺序很重要。我尝试了一些不同的事情,这些事情都感觉很混乱,或者导致了错误。例如:
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>
Run Code Online (Sandbox Code Playgroud)
测试每一项内容的最佳方法是什么?
您可以将每个li的文本收集为一个数组:
all('li span.title').map(&:text)
Run Code Online (Sandbox Code Playgroud)
然后,您可以将该数组与期望的内容进行比较。假设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)
Run Code Online (Sandbox Code Playgroud)
鉴于有多个要检查的部分,遍历每个元素可能比在每个部分上重复上述操作更容易:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2739 次 |
| 最近记录: |