my rspec test won't pass: Michael Hartl's

2019-06-17 02:47发布

问题:

I am at the end of chapter five doing the exercises. I am supposed to be testing that the links go to the correct pages. Here is my test code.

require 'spec_helper'

describe "LayoutLinks" do

    it "should have the right links on the layout" do
        visit root_path
        click_link "About"
        response.should have_selector('title', :content => "About")
        click_link "Home"
        response.should have_selector('title', :content => "Home")
        click_link "Help"
        response.should have_selector('title', :content => "Help")
        click_link "Contact"
        response.should have_selector('title', :content => "Contact")
        click_link "Sign up now!"
        response.should have_selector('title', :content => "Sign up")
        end
        end

Everything passes except for the last test. It says that it can not find a link with the text "Sign up now!" . I know that the page does have a "Sign up now!" link. I thought that maybe it rendered differently in the source code, but when I look at the source code it looks normal <a href="/signup" class="signup_button round">Sign up now!</a> . From my understanding, it is supposed to click on the links and then test if the title matches the :content symbol. Am I misunderstanding something?

here is the error I am getting:

Failures:

  1) LayoutLinks should have the right links on the layout
     Failure/Error: click_link "Sign up now!"
     Webrat::NotFoundError:
       Could not find link with text or title or id "Sign up now!"

回答1:

I believe the problem is that the "Sign up now!" link is in fact not on all pages, and this test actually navigates the pages.

At least in the version of this tutorial that I ran through some time ago, that link was only on the home page.

If you add a visit root_path just before that last click_link it'll likely work.

A better test would have that check in an independent test related specifically to the home page.



回答2:

Also, the title text is "Sign Up". Capital 'U'.

The line needs to be:

response.should have_selector('title', :content => "Sign Up")

The prior answer's advice to do a visit root_path is unneeded if the page visited just before this one is "Home"



回答3:

The reason the test will not work is because you need to run:

$ rake db:test:prepare  

At least, that was why my tests were not passing.

I found the solution in this forum