Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capybara can't find link on the page

I'm trying to get my first capybara tests going. I following Ryan Bate's philosophy and putting some functional tests into my controller spec files.

describe UsersController do
  render_views

  it "can get the home page" do
    get 'home'
    response.body.should include("Login")
  end

  it "should log in" do
    get 'home'
    puts response.body
    click_link('Login')
    response.body.should include("Email")
    response.body.should include("Password")
  end

end

In it should login I ran into problems so began with just trying to make sure I can find and click the link. No luck. In the test as above I'm just trying to make sure the link exists

The puts response.body produces the following output

...
  <div id="user_nav">
      <a href="/users/sign_up">Register</a> or <a href="/users/sign_in" id="Login">Login</a>
  </div>
...

and I also see the element on the actual page. It seems only my test can't find it. The first test does pass.

 1) UsersController should log in
     Failure/Error: click_link('Login')
     Capybara::ElementNotFound:
       no link with title, id or text 'Login' found
     # (eval):2:in `click_link'
     # ./spec/controllers/users_controller_spec.rb:14:in `block (2 levels) in <top (required)>'

I'm using Rails 3.2, Rpsec 2.11 and Capybara 1.1.2.

(I've already checked the other questions on stackoverflow as well as a few tutorials and screencasts. I can't see any reason it can't find an element given an id tag, but I'm probably missing something obvious.

like image 578
hershey Avatar asked Jan 15 '23 17:01

hershey


1 Answers

I think the reason it's not working is that you're using get for what is essentially an integration test. See this post: http://blog.plataformatec.com.br/2012/06/improving-the-integration-between-capybara-and-rspec/

If my understanding is correct, you need to use visit in order to use click_link on the page:

it "should log in" do
  visit home_path
  click_link('Login')
  page.should ...
end

See also this answer on SO: Rspec and capybara, difference between visit and get methods, with regards to the current_path object

like image 66
Chris Salzberg Avatar answered Jan 30 '23 20:01

Chris Salzberg