Things I Learned While Working With Capybara
I have been testing a website with help of Rspec, Cucumber and Capybara with Selenium. Mainly I am using Capybara for selecting and filling up textfields. It is very easy finding any element with Capybara’s find because it looks for name/id/label text for matching element. Check Check Your Web-App’s Functionality Using Rspec, Cucumber And Capybara With Selenium. In perfect world, it is more than enough. But we dont live in perfect world – we live in a world where multiple elements have same id/name or an element without any name/id. How do we find those elements? Fortunately Capybara allows selecting element using XPath. Xpath makes it easy to find any element which does not have id and or name. I will be updating this post as I learn more and more. Now lets checkout some scenario
Click the first button of two button with same Id. all() returns multiple element if found and we can access it like / etc. Capybara allows chaining so we can add click at the end. We can use first() but it is nice know there is option to get element by .
Find a button which does not have any attribute except value.
find(:xpath, '//button[contains(text(), "Click Me")]').click
Select a option from select-box. We can use select() but our select-box does not have id/name.
find(:xpath, '//option[contains(text(), "Apple")]', 'Apple').select_option
Chaining set with find() to set values for input fields
Find a button using class attribute
Upload image using send_keys. In this case file field is not as it normally is.
<input type="file" multiple="multiple" accept="image/jpeg,image/gif,image/png" style="font-size: 999px; position: absolute; width: 100%; height: 100%;"> page.driver.browser.all(:xpath, '//input[@accept="image/jpeg,image/gif,image/png"]').send_keys(Dir.getwd + 'img.jpg')
Increase default_wait_time when you are working with asynchronous ajax which is 2 secs by default. If your internet speed it good then you do not need to change it but if you have bad internet then I will suggest you to increase it. I add this line in spec_helper.rb
Capybara.configure do |config| config.default_wait_time = 7 end
When you want to test subdomains then use visit. What I do is create new helpers like mobile_customer_service_helpers.rb and use a class variable.
module Features module MobileCustomerServiceHelpers @@mobile_subdomain = 'http://m.site.com' def mobile_fill_up_customer_service(url = '/', name, email) visit @@mobile_subdomain + url fill_in 'name', with: name fill_in 'email', with: email click_button 'Send' end end end
We can actually loop through page.should.
scenario 'Looping through all the prices' do CSV.foreach("prices.csv") do |row| fill_in 'price', with: row page.should have_css(".text-error", :text => "Please write a price for your ad") end end
To choose the second item in a select box –