Reputation: 3597
I just completed the Chapter 5 exercises from "The Ruby on Rails tutorial" by Michael Hartl (which is really great) But exercise 4 from section 5.6, I just don't understand how it works.
I have created integration tests using rspec located in spec/requests/static_pages_spec.rb:
shared_examples_for "all static pages" do
it { should have_selector('h1', text: heading) }
it { should have_title(full_title(page_title)) }
end
The full_title function is located in a support directory under 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
Which works great. In exercise 4 in 5.6 we are tasked to remove it by adding a helpers directory and application_helper_spec.rb file 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
and edit utilities.rb to contain just one line spec/support/utilities.rb:
include ApplicationHelper
and all of my tests pass!
My question is how..? How, after removing the full_title util function and only adding the application_helper_spec to test full_title do my original spec tests pass?
Upvotes: 0
Views: 566
Reputation: 59
If you read the question carefully, he's suggesting that there's redundancy in the code that you can refactor further:
"Eliminate the need for the full_title test helper in Listing 5.29 by writing tests for the original helper method, as shown in Listing 5.41."
If we look at listing 5.29, he follows with:
"Of course, this is essentially a duplicate of the helper in Listing 4.2, but having two independent methods allows us to catch any typos in the base title. This is dubious design, though, and a better (slightly more advanced) approach, which tests the original full_title helper directly, appears in the exercises (Section 5.6)."
So, actually, you have already defined this function in your app/helpers/application_helper.rb file. A simple include statement in your spec/support/utilities.rb file will load all of your functions from app/helpers/application_helper.rb and that is why your tests still pass.
Have fun with the rest of the tutorial!
Upvotes: 3