【问题标题】:Capybara testing with RSpec in RubyCapybara 在 Ruby 中使用 RSpec 进行测试
【发布时间】:2021-07-27 16:15:41
【问题描述】:

在我的索引页面上,我有这个 div:

<div class="banner">
  <h1 class="glow-header">Galaxy Far, Far Away? Quick Trip to Mars?<br>
    Pianeta has you covered.</h1>
<div>

在我的测试文件中这是有效的:

RSpec.describe 'home features' do
  it 'displays the name of the app and links to the index-all planets page' do
    visit root_path
    expect(page).to have_content('Space is full of surprises.')
    click_link('Go Beyond')
    expect(current_path).to eq('/planets')
    expect(page).to have_content('Galaxy Far, Far Away?')
  end
end

但我希望它与包含的 h1 一起使用。 我这样做了:

expect(page).to have_content('<h1 class="glow-header">Galaxy Far, Far Away? Quick Trip to Mars?<br>
    Pianeta has you covered.</h1>')
end

但是测试失败了。我做错了什么?

【问题讨论】:

    标签: ruby-on-rails rspec capybara system-testing


    【解决方案1】:

    #has_content?/#has_text? 方法只检查页面的文本内容。它不查看 HTML 标记。

    如果你想检查特定 HTML 元素中的内容,有一个 #within 方法,它接受一个块并将其中的 Capybara 查找范围限定在匹配的元素内。 #within 引用的元素必须存在,否则 Capybara 会引发异常。

    page.within('h1.glow-header') do
      expect(page).to have_content('Galaxy Far, Far Away?')
    end
    

    【讨论】:

    • 是的,您可能还想在 HTML 标记中添加 ID 或其他内容,因为类名非常通用,如果您在页面上使用两次,代码就会中断。
    【解决方案2】:

    如果您不想使用 within 处理范围限定,您可以这样做

    expect(page).to have_css('h1.glow-header', text: 'Galaxy Far, Far Away?')
    

    如果您已经获得了对标头的引用,您还可以执行类似的操作

    header = find('h1.glow-header')
    ...
    expect(header).to have_text('Galaxy Far, Far Away?')
    

    另外你不应该做expect(current_path).to eq('/planets')。将 RSpecs eq 匹配器与 Capybara 一起使用会在您转向使用异步(支持 JS)驱动程序时导致不稳定的测试,因为它会阻止 Capybara 自动等待/重试行为。相反,您应该使用 Capybara 提供的匹配器

    expect(page).to have_current_path('/planets')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-04
      相关资源
      最近更新 更多