Reputation: 3345
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 ?
Upvotes: 22
Views: 17323
Reputation: 4479
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
Upvotes: 2
Reputation: 11
My example for this
find("ol.nya-bs-select.btn-default.form-control[ng-model='scope.values.countries']")
.find_button("Nothing selected").click
Upvotes: 1
Reputation: 2200
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.
Upvotes: 4
Reputation: 3345
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
Upvotes: 6
Reputation: 17480
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'
Upvotes: 8