简体   繁体   中英

How do I get this rspec test to pass?

I can't for the life of me figure out why these tests are failing.

When a user puts in their email/password and hits the Log in button, they are redirected to their profile page which puts their first name in the title and displays their first name on the page. It also shows a link to their profile and a sign out link. When I went through the steps in the browser everything was where it should be, but when rspec runs it continues to fail.

What I find really odd is that when I run a user_page_spec test that tests the same elements, those all pass.

I figure it has to do with either the click_button part or the "redirect_to user" in the controller, but any insight would be much appreciated.

Here are the tests-

Passing tests in user_pages_spec.rb-

describe "profile page" do
    let(:user) {  FactoryGirl.create(:user)  }
    before {  visit user_path(user)  }

    it {  should have_selector('h1',    text: user.firstName)  }
    it {  should have_selector('title', text: user.firstName)  }
end

Failing tests in authentication_pages_spec.rb - require 'spec_helper'

describe "Authentication" do
    describe "sign in" do
    .
    .
    .
    describe "with valid information" do
        let(:user) {  FactoryGirl.create(:user)  }
        before do
            fill_in "Email",            with: user.email
            fill_in "Password",     with: user.password
            click_button "Log in"
        end

        it {  should have_selector('title', text:user.firstName)  }
        it {  should have_link('Profile', href: user_path(user))  }
        it {  should have_link('Sign out', href: signout_path)  }

        describe "followed by signout" do
            before {  click_link "Sign out"  }
            it {  should have_link('Home')  }
        end
    end
  end
end

Yup. It's always the simplest of oversights that cause the biggest of headaches.

Here is what happened.

Rather than using the following-

describe "page" do
  it "should have something" do
    page.should have_selector('')
  end
end

Rspec lets you define a subject -

subject {  page  }

Which allows you to simplify the first code block to the following-

subject {  page  }
describe "page" do
  it {  should have_selector('')  }
end

This allows you to run multiple tests which reference the page without all the extra typing.

I left out the subject { page } at the very top, so none of my it {} blocks knew what to reference. As soon as that was added in, all tests passed with no problems.

Hope this helps someone else out in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM