has_selector在RSpec测试中失败,但页面呈现正确并且标记存在

Ste*_*e T 2 rspec ruby-on-rails webrat

我正在通过Hartl的Rails Tutorial一书,我完全坚持其中一个测试.测试(从书中直接)非常简单:

require 'spec_helper'
describe UsersController do
render_views
describe "GET 'show'" do
    before(:each) do
        @user = Factory(:user)
    end
    ...
    it "should include the user's name" do
        get :show, :id => @user
        response.should have_selector('h1', :content => @user.name)
    end
end
Run Code Online (Sandbox Code Playgroud)

测试失败,出现以下错误:

UsersController GET 'show' should include the user's name Failure/Error: response.should have_selector('h1', :content => @user.name) expected following output to contain a <h1>Steve T</h1> tag:...

页面在浏览器中正确呈现.这是从浏览器呈现的HTML源中剪切的:

<section class="round">
<h1> <img alt="Steve T" class="gravatar" src="http://gravatar.com/..." /> Steve T </h1> </section>

我甚至可以print response.body在控制器规范中添加一个调用:它将正确输出标签.

关于我可能做错的任何想法?

更新 - 似乎我们已经确定了一个可能很重要的项目:rspec测试失败消息中的HTML缺少body标记内的所有内容.

1) UsersController GET 'show' should include the user's name Failure/Error: response.should have_selector('h1', :content => @user.name) expected following output to contain a <h1>Steve T</h1> tag: <!DOCTYPE html> <html><head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Ruby on Rails Tutorial Sample App | Steve T</title> </head></html> # ./spec/controllers/users_controller_spec.rb:33:in block (3 levels) in <top (required)>'

有谁知道为什么,如果浏览器中的页面包含<body>标签和内部内容,如果print response.body显示内容,为什么错误消息会跳过它?

小智 8

在使用Rails教程时遇到了类似的问题.我忘了在顶部'describe'语句下面加入'render_views',这导致'have_selector'测试失败.