使用rspec和assert_select

时间:2016-08-31 21:03:13

标签: ruby-on-rails ruby rspec

我目前正在通过重写rspec中的所有Rails Tutorial(Hartl)测试来学习rspec。我在使用rspec测试链接是否存在问题。 无论出于何种原因,我的测试在它看起来肯定应该通过时失败了;有明确指向网址的链接,但它总是说找到了0。

以下是我的rspec代码,用于测试是否存在两个到根路径的链接:

require 'spec_helper'
require 'rails_helper'

describe StaticPagesController, :type => :view do

  it "root path contains all expected links" do 
    render :template => 'static_pages/home'
    puts response.body
    assert_template 'static_pages/home'
    assert_select "a[href=?]", "/", count: 2
  end
end

以下是我的错误消息:

waynesun95:~/workspace/sample_app (advanced-login) $ bundle exec rspec
RubyDep: WARNING: Your Ruby is outdated/buggy. (To disable warnings, set RUBY_DEP_GEM_SILENCE_WARNINGS=1)
RubyDep: WARNING: Your Ruby is: 2.3.0 (buggy). Recommendation: install 2.3.1.
<div class="center jumbotron">  
  <h1>Welcome to the Sample App</h1>
  <h2>
    This is the home page for the 
    <a href="http://www.railstutorial.org/">Ruby on Rails Tutorial</a>
    sample application.
  </h2>

  <a class="btn btn-lg btn-primary" href="/signup">Sign up now!</a>
</div>

<a href="http://rubyonrails.org/"><img alt="Rails logo" src="/assets/rails-c094bc3a4bf50e5bb477109e5cb0d213af27ad75b481c4df249f50974dbeefe6.png" /></a>
......F

Failures:

  1) StaticPagesController root path contains all expected links
     Failure/Error: assert_select "a[href=?]", "/", count: 2

     Minitest::Assertion:
       Expected exactly 2 elements matching "a[href="/"]", found 0..
       Expected: 2
         Actual: 0
     # ./.bundle/ruby/2.3.0/gems/minitest-5.9.0/lib/minitest/assertions.rb:139:in `assert'
     # ./.bundle/ruby/2.3.0/gems/minitest-5.9.0/lib/minitest/assertions.rb:174:in `assert_equal'
     # ./.bundle/ruby/2.3.0/gems/rails-dom-testing-1.0.7/lib/rails/dom/testing/assertions/selector_assertions.rb:278:in `assert_size_match!'
     # ./.bundle/ruby/2.3.0/gems/rails-dom-testing-1.0.7/lib/rails/dom/testing/assertions/selector_assertions.rb:175:in `block in assert_select'
     # ./.bundle/ruby/2.3.0/gems/rails-dom-testing-1.0.7/lib/rails/dom/testing/assertions/selector_assertions.rb:174:in `tap'
     # ./.bundle/ruby/2.3.0/gems/rails-dom-testing-1.0.7/lib/rails/dom/testing/assertions/selector_assertions.rb:174:in `assert_select'
     # ./spec/users_signup_spec.rb:16:in `block (2 levels) in <top (required)>'

Finished in 0.47062 seconds (files took 12.61 seconds to load)
7 examples, 1 failure

Failed examples:

rspec ./spec/users_signup_spec.rb:6 # StaticPagesController root path contains all expected links

错误消息显示它找到了与[href =“/”]匹配的0个元素。但是,在检查我正在测试的页面时,当我右键单击并在链接到根路径的元素上“检查元素”时,它显然链接到“/”(在下面的图片中突出显示)。  highlighted "Home" link clearly links to the path "/"

此外,我知道我在正确的模板/视图上,因为当我删除assert_select行并且只留下render和assert_template行时,代码通过没有问题(进一步证明这是因为我得到一个错误我改变了assert_template中的路径。

我不知道发生了什么事。它似乎应该通过测试但它不是,我尝试的任何东西似乎都没有。非常感谢任何帮助!

0 个答案:

没有答案