【发布时间】:2013-08-13 22:13:56
【问题描述】:
我正在阅读 Hartl 的 Rails 教程一书,但我完全卡在了其中一个测试上。测试(来自书中)非常简单:
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
测试失败并出现以下错误:
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 缺少其中的正文标记。
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显示内容,为什么错误消息会跳过它?
【问题讨论】:
-
请注意,但我认为 have_selector 完全匹配?在您的情况下,H1 包含嵌入式 IMG。我想如果那个 IMG 不在那里,它会起作用。试过了吗?我相信
have_selector是一个 webrat 匹配器。你可能想试试response.should contain(@user.name)。或者这个可能工作:response.should have_selector('h1 img', :content => @user.name). -
据我所知,这正是正在发生的事情。
标签: ruby-on-rails rspec webrat