我正在进行Michael Hartl's Rails Tutorial的第5章练习,并试图了解Rails / Rspec如何在full_title
中测试辅助方法app/helpers/application_helper.rb
。我的所有测试都在spec/requests/static_pages_spec.rb
,在其中,我正在调用full_title
以减少代码膨胀。
因此,为了测试原始full_title
,我在spec/helpers/application_helpers_spec.rb
中创建了一个测试,并通过spec/support/utilities.rb
包含它。代码正在传递,但我想了解正在进行的过程(对操作的顺序)。谢谢。
我可以这样想吗?
static_pages_spec.rb
(包括utilities.rb
)static_pages_spec.rb
application_helper_spec.rb
describe "full_title" do
application_helper_spec.rb
full_title
方法并完成application_helper_spec.rb
, iterating through above process when
full_title`被调用。static_pages_spec.rb
require 'spec_helper'
describe "Static pages" do
subject { page }
shared_examples_for "all static pages" do
it { should have_selector('h1', text: heading) }
it { should have_selector('title', text: full_title(page_title)) }
end
describe "Home page" do
before { visit root_path }
let(:heading) { 'Sample App' }
let(:page_title) { '' }
it_should_behave_like "all static pages"
it { should_not have_selector 'title', text: '| Home' }
end
describe "Help page" do
before { visit help_path }
let(:heading) { 'Help' }
let(:page_title) { 'Help' }
it_should_behave_like "all static pages"
end
describe "About page" do
before { visit about_path }
let(:heading) { 'About' }
let(:page_title) { 'About Us' }
it_should_behave_like "all static pages"
end
describe "Contact page" do
before { visit contact_path }
let(:heading) { 'Contact' }
let(:page_title) { 'Contact' }
it_should_behave_like "all static pages"
end
it "should have the right links on the layout" do
visit root_path
click_link "About"
page.should have_selector 'title', text: full_title('About Us')
click_link "Help"
page.should have_selector 'title', text: full_title('Help')
click_link "Contact"
page.should have_selector 'title', text: full_title('Contact')
click_link "Home"
page.should have_selector 'title', text: full_title('')
click_link "Sign up now!"
page.should have_selector 'title', text: full_title('Sign up')
click_link "sample app"
page.should_not have_selector 'title', text: full_title('| Home')
end
end
application_helper_spec.rb
require 'spec_helper'
describe ApplicationHelper do
describe "full_title" do
it "should include the page title" do
full_title("foo").should =~ /foo/
end
it "should include the base title" do
full_title("foo").should =~ /^Ruby on Rails Tutorial Sample App/
end
it "should not include a bar for the home page" do
full_title("").should_not =~ /\|/
end
end
end
application_helper.rb
module ApplicationHelper
#Returns the full title on a per-page basis.
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
end
答案 0 :(得分:1)
以这种方式思考:
static_pages_spec.rb
(包括utilities.rb)中调用的'full_title'正在运行application_helper.rb中描述的'full_title'方法。
application_helper_spec.rb
验证通过full_title传递的字符串/值(page_title)。
如果我没有弄错的话,每次在测试中调用full_title
方法时都会这样做。