Rspec test should pass but fails

2019-02-19 07:27发布

I have this test from michael hartl book:

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

And the view:

<% 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>

When I run the test it says:

....

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

But It should pass, because when I view the page in browser the title is: Ruby on Rails Tutorial Sample App | Sample App, which is correct!

4条回答
姐就是有狂的资本
2楼-- · 2019-02-19 07:51

For the time being, you should do what @dimuch suggests and make sure you specify the same Capybara version Michael Hartl uses in the tutorial (1.1.2).

If you want to upgrade to Capybara 2.0 in the future and keep your tests for titles, have a look at this StackOverflow answer for a guide to creating a RSpec matcher that will do what you're expecting.

查看更多
对你真心纯属浪费
3楼-- · 2019-02-19 07:52

Make sure you're using capybara 1.1.2 in your Gemfile. Starting from 2.0 capybara does not works for title testing (https://github.com/jnicklas/capybara/issues/844)

...
group :test do
  gem 'capybara', '1.1.2'
end
查看更多
smile是对你的礼貌
4楼-- · 2019-02-19 07:52

I've been using the following and they have been posting green. I dropped have_selector and went with have_title.

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

-- and --

it { should have_title(user.name) }

This is with capybara 2.2.0.

查看更多
走好不送
5楼-- · 2019-02-19 08:05

Using capubara 2.0 you should use

page.should have_title("The title")

But in aint work if you dont add

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

To your application.html

page.title # => "The title"
page.has_title?("The title") # => true
page.should have_title("The title")
查看更多
登录 后发表回答