in this chapter,we will see a very simple integration test to test routes in rails.
controller test is only able to test routes inside the controller, so if you want to test global routes, like home page "/home", "/about", you will need integration test, integration test can test across all controllers, it is like the browsers are accessing our app.
(testing routes is just the beginning of integration test.)
right now, our app doesn't have these routes, yet, we first write the test, then implement the route, this is so called test driven dev, TDD
we start by genrating a integration test:
rails generate integration_test layout_links
since we are using rspec framwork, this command will gen a file
spec/requests/layout_links_spec.rb
in rspec, integration test is called requests, no idea why.
(if you are not using rspec frameword, this command still work, it will gen file to test/integration/layout_links_test.rb)
in this test, we will get some urls, and make sure the right page are rendered.
so we will use
response.should have_selector("title", :content => "title")
below is the code:
require 'spec_helper'
describe "layoutlinks" do
it "should have a home page at '/'" do
get "/"
response.should have_selector("title", :content => "Home")
end
it "should have a about page at '/about'" do
get "/about"
response.should have_selector("title",:content => "About")
end
it "should have a Contact page at '/contact'" do
get '/contact'
response.should have_selector('title', :content => "Contact")
end
it "should have a Help page at '/help'" do
get '/help'
response.should have_selector('title', :content => "Help")
end
end
right now, all these test will fails, as we haven't added the routes yet.
(BTW, if you are running autotest, by default, autotest will not run integration test because it may be slow, if you do want autotest to run integration, (the writer find running integration test is better), you need config autotest in .autotest file
Autotest.add_hook :initialize do |autotest|
autotest.add_mapping(/^spec\/requests\/.*_spec\.rb$/) do
autotest.files_matching(/^spec\/requests\/.*_spec\.rb$/)
end
end
Don't worry about the API of autotest, I don't their mean, I just google to get it and use it.)
2. there is another very important test helper method in rspec:
"visit"
and
"click_link"
visit will visit the path,
click_link will click on the link.
for example:
it "should have the right links" do
visit root_path
click_link "About"
response.should have_selector("title", :content => "About")
end
Very cool, isn't it??