水豚的 within 方法的正确用法是什么?

What is the correct usage of capybara's within method?

对于页脚的功能示例,我使用了以下代码:

feature 'in footer' do
    scenario "has a Copyright text" do
      within('footer') {
        expect(page).to have_content "Copyright"
      }
    end

    scenario "has navigation bar" do
      within('footer') {
        expect(page).to have_selector 'nav ul li'
      }
    end

    scenario "has a link for 'About'" do
      within('footer') {
        expect(page).to have_link 'About', href: '#'
      }
    end
end

如果你仔细观察,我在每个场景中都重复了 "within",这与代码的枯燥性冲突。

我不想在一个场景中包含所有期望,因为我想要对每个期望进行解释。

在这种情况下使用 within 方法的最佳方法是什么?

您可以创建一种方法来消除 within 方法的重复。

例如:

feature 'footer' do
  scenario 'footer has copyright text, navigation bar and link for about' do
    within('footer') {
       expect(page).to have_content "Copyright"
       expect(page).to have_selector 'nav ul li'
       expect(page).to have_link 'About', href: '#'
    }
  end
end

没办法干掉#within的使用还是有多个场景。有人可能会尝试使用 around 过滤器,但由于 around 和 before/after 过滤器的顺序,它不会真正起作用。您可以在不使用 #within 的情况下获得您要查找的内容,方法是在前块中找到页脚,然后期望关闭

before do
  visit('my page')
  @footer = find('footer')
end

scenario 'blah blah' do
  expect(@footer).to have_content('...')
end

我会说编写功能测试只是为了检查页面上的一行文本并不是很好的做法。功能测试有很多开销,检查不依赖于任何用户操作的文本行实际上更适合视图测试而不是功能(您仍然可以在视图测试中使用 Capybaras 匹配器)。功能测试应该用于测试系统中较大的行为。