【问题标题】:RSpec/Capybara testing have_selector conundrumRSpec/Capybara 测试 have_selector 难题
【发布时间】:2014-12-29 18:58:34
【问题描述】:

这是来自 Michael Hartl 的 Ruby on Rails 教程第 2 版。第 3 版(也是当前最新版)没有使用 RSpec 进行测试,所以我决定使用这本书。

我已经阅读了用户的解决方法,并且知道有不同的方法可以编写测试以使其正常工作,但我想使用 have_selector 来保持代码的一致性。任何解释/建议都会非常有帮助。 我不明白为什么下面的测试通过了 h1 元素而不是 title 元素:

spec.rb:

describe "Static pages" do 

  describe "Home page" do

  it "should have the h1 'Sample App'" do
    visit '/static_pages/home'
    expect(page).to have_selector('h1', :text => 'Sample App')
  end

  it "should have the title 'Home'" do
    visit '/static_pages/home'
    expect(page).to have_selector('title', 
                         :text => "Ruby on Rails Tutorial Sample App | Home")
  end
end

home.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Ruby on Rails Tutorial Sample App | Home</title>
</head>
<body>
  <h1>Sample App</h1>

</body>
</html>

【问题讨论】:

  • expect(page).to have_selector('title', ... 之前添加一个save_and_open_page 并直观地验证该页面是否具有&lt;title&gt; 标记。您必须添加 launchy gem 才能使 save_and_open_page 工作。

标签: ruby-on-rails rspec tdd capybara bdd


【解决方案1】:

试试:

expect(page).to have_selector('title', 
                     :text => "Ruby on Rails Tutorial Sample App | Home",
                     :visible => false)

由于标题标签在&lt;head&gt;元素中,它被认为是隐藏的。指定 :visible =&gt; false 会在 have_selector 匹配器中包含这些标签以供考虑。

【讨论】:

    【解决方案2】:

    更新当前水豚最佳实践,因为现在有一个 have_title 匹配器。

    expect(page).to have_title('Ruby on Rails Tutorial Sample App | Home')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-12
      相关资源
      最近更新 更多