3

我从michael hartl书中得到了这个测试:

require 'spec_helper'
  describe "Static pages" do
    let(:base_title) { "Ruby on Rails Tutorial Sample App" }

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

      it "should have the title 'Home'" do
        visit '/static_pages/home'
        page.should have_selector('title', :text => "#{base_title} | Home")
      end
  end
end

和观点:

<% provide(:title, 'Home') %>
<h1>Sample App</h1>
<p>
  This is the home page for the
  <a href="http://railstutorial.org/">Ruby on Rails Tutorial</a>
  sample application.
</p>

当我运行测试时,它说:

....

Finished in 1.91 seconds
4 examples, 0 failures

Randomized with seed 42247

.F...

Failures:

  1) Static pages Home page should have the title 'Home'
     Failure/Error: page.should have_selector('title', :text => "#{base_title} | Home")
       expected #has_selector?("title", {:text=>"Ruby on Rails Tutorial Sample App | Home"}) to return true, got false
     # ./spec/requests/static_pages_spec.rb:16:in `block (3 levels) in <top (required)>'

Finished in 1.91 seconds
5 examples, 1 failure

Failed examples:

rspec ./spec/requests/static_pages_spec.rb:14 # Static pages Home page should have the title 'Home'

Randomized with seed 17491

但它应该通过,因为当我在浏览器中查看页面时,标题是:Ruby on Rails Tutorial Sample App | 示例应用程序,这是正确的!

4

4 回答 4

5

确保在 Gemfile 中使用 capybara 1.1.2。从 2.0 capybara 开始不适用于标题测试(https://github.com/jnicklas/capybara/issues/844)

...
group :test do
  gem 'capybara', '1.1.2'
end
于 2013-01-02T12:51:54.417 回答
3

目前,您应该按照@dimuch 的建议进行操作,并确保您指定 Michael Hartl 在教程 (1.1.2) 中使用的相同 Capybara 版本。

如果您想在将来升级到 Capybara 2.0 并保留您的标题测试,请查看此 StackOverflow 答案,以获取创建 RSpec 匹配器的指南,该匹配器将满足您的期望。

于 2013-01-02T14:07:38.663 回答
3

使用 capubara 2.0 你应该使用

page.should have_title("The title")

但是如果您不添加,则无法正常工作

<style type="text/css">head, head title { display: block }</style>

到您的 application.html

page.title # => "The title"
page.has_title?("The title") # => true
page.should have_title("The title")
于 2013-04-25T07:51:13.223 回答
0

我一直在使用以下内容,他们一直在发布绿色。我放弃了 have_selector 并选择了 have_title。

it { should have_title( full_title('Sign up') ) }

- 和 -

it { should have_title(user.name) }

这是水豚2.2.0。

于 2014-03-12T16:44:14.450 回答