Rspec的测试应该通过,但是失败(Rspec test should pass but fails

2019-07-17 18:06发布

我从这个测试迈克尔·哈特尔书:

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的教程示例应用程序| 应用程序示例,这是正确的!

Answer 1:

请确保你使用的水豚1.1.2在你的Gemfile。 2.0水豚开始并不适用于标题测试(https://github.com/jnicklas/capybara/issues/844)

...
group :test do
  gem 'capybara', '1.1.2'
end


Answer 2:

暂且,你应该做的@dimuch暗示什么,并确保你指定相同的水豚版本的迈克尔·哈特尔使用教程(1.1.2)。

如果你想升级到2.0水豚在未来,并保持你的测试标题,看看这个StackOverflow的答案为指导,以创建一个RSpec的匹配,会做你期待什么。



Answer 3:

使用capubara 2.0,你应该使用

page.should have_title("The title")

但在AINT工作,如果你不加

<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")


Answer 4:

我一直在使用以下命令,他们已经张贴绿色。 我放弃了have_selector与have_title去。

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

- 和 -

it { should have_title(user.name) }

这与水豚2.2.0。



文章来源: Rspec test should pass but fails