Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use capybara in rspec to click on a dropdown option

Tags:

I am using ruby on rails 3.2.3 and capybara to help creating request spec. My goal is to create a spec request that test the log out. The web page:

<li class="dropdown">   <a class="dropdown-toggle" data-toggle="dropdown">     Welcome <%= current_user.first_name + " "+ current_user.last_name%>     <b class="caret"></b>   </a>   <ul class="dropdown-menu">     <a href="#">       <%= link_to "Sign out", destroy_user_session_path, :method => :delete%>     </a>   </ul> </li> 

For the test, I have

describe "sign out" do   it "should let user to sign out" do     login_as user, :scope => :user     # click_on "Welcome #{user.first_name} #{user.last_name}"     # Now click on Sign out   end end 

I don't know how to click on the Sign out using capybara because it is in a drop down menu, therefore not visible on page. Does anyone know ?

Is there any other way to click on an element in a dropdown menu ?

like image 528
u19964 Avatar asked Jun 29 '12 22:06

u19964


People also ask

How do you select options in capybara?

Method: Capybara::Node::Actions#select If from option is present, #select finds a select box, or text input with associated datalist, on the page and selects a particular option from it. Otherwise it finds an option inside current scope and selects it.

What is Rspec capybara?

Capybara is a web-based test automation software that simulates scenarios for user stories and automates web application testing for behavior-driven software development. It is written in the Ruby programming language.

How do I check a checkbox in capybara?

Method: Capybara::Node::Actions#check The check box can be found via name, id, test_id attribute, or label text. If no locator is provided this will match against self or a descendant.


2 Answers

I've tested a dropdown just by clicking both links

click_link "Welcome #{current_user.first_name} #{current_user.last_name}" click_link 'sub link' 
like image 186
DVG Avatar answered Sep 28 '22 03:09

DVG


Hello I figured it out eventually. I had to use xpath to find the link. Based on the html above, here is what I did:

In rspec, I wrote:

page.find(:xpath, "//a[@href='/users/sign_out']").click 

The reason I use "//a[@href='/users/sign_out']" is because the link_to "Sign out", destroy_user_session_path, :method => :delete is compiled to <a href="/users/sign_out" ... on the web page.

And it works :-)

Oh by the way, I found this useful link: http://www.suffix.be/blog/click_image_in_link_capybara

like image 29
u19964 Avatar answered Sep 28 '22 05:09

u19964