我刚从 Michael Hartl 完成了“The Ruby on Rails tutorial”的第5章练习(这真的很棒)但是从5.6节练习4,我只是不明白它是如何工作的。
我使用位于spec / requests / static_pages_spec.rb中的rspec创建了集成测试:
shared_examples_for "all static pages" do
it { should have_selector('h1', text: heading) }
it { should have_title(full_title(page_title)) }
end
full_title 函数位于spec / support / utilities.rb下的支持目录中:
def full_title(page_title)
base_title = "Ruby on Rails Tutorial Sample App"
if page_title.empty?
base_title
else
"#{base_title} | #{page_title}"
end
end
哪个效果很好。在5.6的练习4中,我们的任务是通过添加一个帮助程序目录和application_helper_spec.rb文件spec / helpers / application_helper_spec.rb来删除它:
require 'spec_helper'
describe ApplicationHelper do
describe "full_title" do
it "should include the page title" do
expect(full_title("foo")).to match(/foo/)
end
it "should include the base title" do
expect(full_title("foo")).to match(/^Ruby on Rails Tutorial Sample App/)
end
it "should not include a bar for the home page" do
expect(full_title("")).not_to match(/\|/)
end
end
end
并编辑utilities.rb以仅包含一行规范/ support / utilities.rb:
include ApplicationHelper
我的所有测试都通过了!
我的问题是如何......?在删除 full_title util函数并仅添加 application_helper_spec 以测试 full_title 之后,我的原始规范测试是如何通过的?
答案 0 :(得分:3)
如果您仔细阅读该问题,他建议代码中存在可以进一步重构的冗余:
"在清单5.29中消除了对full_title测试助手的需求 为原始帮助器方法编写测试,如清单所示 5.41"
如果我们看一下5.29的清单,他会跟着:
"当然,这实际上是清单中助手的副本 4.2,但有两个独立的方法允许我们捕获基本标题中的任何拼写错误。这是可疑的设计,但更好 (略高级)方法,用于测试原始的full_title 直接帮助,出现在练习中(第5.6节)。"
实际上,您已经在app / helpers / application_helper.rb文件中定义了此函数。 spec / support / utilities.rb文件中的简单include语句将从app / helpers / application_helper.rb加载所有函数,这就是你的测试仍然通过的原因。
与本教程的其余部分一起玩得开心!