I look through the book "Ruby on Rails 3 Tutorial" and stumbled upon the part where I have to write some basic unit tests for my static pages. I noticed that the code only replicates with some text changes, so I modify it like this:
require 'spec_helper' describe PagesController do render_views pages = ['home', 'contact', 'about', 'help'] before(:each) do @base_title = "Ruby on Rails Tutorial Sample App | " end pages.each do |page| describe "GET '#{page}'" do it "should be successful" do get "#{page}" response.should be_success end it "should have the right title" do get "#{page}" response.should have_selector("title", :content => @base_title + page.capitalize) end end end end
In the above example, I am confused by the fact that I can replace the variable "pages" as follows:
@pages = ['home', 'contact', 'about', 'help']
And it still works. Why is this? How are "pages and pages" different?
Another confusing thing is that both of these causes test failures:
pages = ['home', 'contact', 'about', 'help'] @base_title = "Ruby on Rails Tutorial Sample App | "
and
before(:each) do pages = ['home', 'contact', 'about', 'help'] @base_title = "Ruby on Rails Tutorial Sample App | " end
Why don't the above examples work? Why should the code look like I wrote in my first piece of code? I assume this has something to do with the scope variable, but I'm still new to Ruby, so I'm looking for a deeper understanding.
FWIW, I am an experienced C # developer, so getting comparable Java or C # code will help me understand this or a well-written description.
Thanks for any support.
Edit: Added error message when I move @base_title outside the "before" block.
Failure/Error: response.should have_selector("title", :content => @base_title + page.capitalize) NoMethodError: You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.+ # ./spec/controllers/pages_controller_spec.rb:21:in `block (4 levels) in <top (required)>'