RSpec/Capybara测试中的have_selector难题

7
这是来自 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 并直观地验证页面确实有 <title> 标签。您需要添加 launchy gem 才能使 save_and_open_page 正常工作。 - Prakash Murthy
2个回答

9

请尝试:

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

由于标题标签位于元素中,因此它被视为隐藏元素。使用:visible => false指定会考虑这些标签,在have_selector匹配器中显示出来。

3

由于现在有了 have_title 匹配器,因此更新当前 capybara 最佳实践。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接