Rspec测试视图测试失败但HTML没问题?

时间:2014-03-31 17:47:39

标签: ruby-on-rails ruby rspec

使用Rspec,我正在测试navnar中徽标的存在:

#spec/views/_header_spec.html.erb
require 'spec_helper'

describe "layouts/_header.html.erb" do
  subject{rendered}


  it "should have the clickable logo" do
    render
    should have_selector("img")
    should have_link("/")
  end
end

这是我生成的HTML:

<a href="/" class="navbar-brand">
  <img alt="Logo" src="/assets/logo.png">
</a>

页面没问题,但测试失败了:

$rspec spec/views/_header_spec.rb 
F

Failures:

  1) layouts/_header.html.erb should have the clickable logo
     Failure/Error: should have_link("/")
     Capybara::ExpectationNotMet:
       expected to find link "/" but there were no matches
     # ./spec/views/_header_spec.rb:10:in `block (2 levels) in <top (required)>'

Finished in 0.13914 seconds
1 example, 1 failure

Failed examples:

rspec ./spec/views/_header_spec.rb:7 # layouts/_header.html.erb should have the clickable logo

Randomized with seed 37707

测试失败,但HTML行为页面是正确的,所以我认为我的测试无法正常工作。你能帮助我吗?

1 个答案:

答案 0 :(得分:2)

替换

should have_link("/")

使用

should have_link("Logo", href: "/")

have_link获取图片的display text链接或alt属性值,并使用href选项指定相应的路径。