简体   繁体   中英

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

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 ?

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'

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

A much easier solution is simply this:

select("option you want to select from menu", :from => "label name")

NOTE: The "label name" is the actual text of the <label> . However, you can also use the "id" or "name" attribute of the <select> here as well, which I think is better since you may change the label text at some point and if you do, your tests will still pass.

My example for this

find("ol.nya-bs-select.btn-default.form-control[ng-model='scope.values.countries']")
    .find_button("Nothing selected").click

I had a similar problem, but my dropdown didn't have any text, only icons:

%li#user-menu.dropdown
  %a.dropdown-toggle{ href: "#", data: { toggle: "dropdown" }, role: "button", aria: { haspopup: "true", expanded: "false" } }
    %i.fa.fa-user
    %span.caret
  %ul.dropdown-menu
    %li.logout-text= link_to "Log Out", destroy_user_session_path, :method => :delete

In my spec I used:

def when_I_sign_out
  find('#user-menu').click
  click_on 'Log Out'
end

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