【问题标题】:Testing page title with Capybara 2.4 and rspec 3 and rails 4使用 Capybara 2.4 和 rspec 3 和 rails 4 测试页面标题
【发布时间】:2014-12-30 23:00:04
【问题描述】:

我正在尝试在 rails 中测试我的静态页面的标题。我正在使用 Capybara 2.4.4 和 rspec 3。

我的测试如下所示 static_pages_controller_spec.rb

require 'spec_helper'
require 'rails_helper'
describe StaticPagesController do
  describe "GET 'Index'" do
    it "should be successful" do 
      visit root_path
      response.should be_success
    end

    it "should have the right title" do
      visit root_path
      expect(page).to have_selector('title', 
                     :text => "Index",
                     :visible => false)
    end 
  end
end

页面确实设置了正确的标题。 我收到的错误如下

Failure/Error: expect(page).to have_selector('title',
       expected to find css "title" with text "Index" but there were no matches

【问题讨论】:

  • 你应该期望 page(page).to have_content 代替
  • 或许贴出视图代码?
  • stackoverflow.com/questions/13573525/…这应该有你的答案。
  • @trueinViso 我尝试了最新的答案并收到预期的“”以包含“索引”错误
  • 你试过expect(page).to have_title "Index"?你正在测试的页面上有<title>Index<\title>?只是为了确保您在测试中执行了save_and_open_page 并检查了元素以确保 html 存在?

标签: ruby-on-rails ruby-on-rails-4 rspec capybara


【解决方案1】:

我也花了好几个小时试图弄清楚。

最终起作用的是这个

将 capybara 安装为 gem

group :test do
  gem 'rspec'
  gem 'capybara'
end

然后运行bundle install

将以下内容添加到 spec/spec_helper.rb 的顶部

require 'capybara/rails'
require 'capybara/rspec'

然后在 RSpec.configure 中,添加 config.include Capybara::DSL

RSpec.configure do |config|
  .
  .
  .
  config.include Capybara::DSL
end

然后在你的pages_controller_spec.rb中,修改使用如下。

请注意,我已包含Capybara.ignore_hidden_elements = false

describe PagesController do
  render_views
  Capybara.ignore_hidden_elements = false

  describe "GET 'home'" do
    it "should be successful" do
      get 'home'
      response.should be_success
    end
    it "should have the right title" do
      get 'home'
      response.body.should have_xpath("//title",:text => "ROR")
    end
  end

end

Check my repository 如果您想查看其他内容

以下备忘单也应该派上用场
https://gist.github.com/them0nk/2166525

【讨论】:

  • 我很抱歉没有早点回来。我只是尝试实施您的解决方案,但仍然无法正常工作。我收到“期望找到带有文本“TITLE”的 xpath“//title”,但没有匹配项”。
猜你喜欢
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多