当前位置: 首页 > 工具软件 > Capybara > 使用案例 >

Ruby学习笔记(22)_capybara基础方法

年风华
2023-12-01

项目使用了capybara,在github中研究了下资料, 这里记录下常用的简单方法. 更多详情查看—>Github_Capybara

Note: By default Capybara will only locate visible elements. This is because a real user would not be able to interact with non-visible elements.

Note: All searches in Capybara are case sensitive. This is because Capybara heavily uses XPath, which doesn’t support case insensitivity.


You can use the visit method to navigate to other pages:

    visit('/projects')
    visit(post_comments_path(post))

The visit method only takes a single parameter, the request method is always GET.

You can get the current path of the browsing session, and test it using the have_current_path matcher:

    expect(page).to have_current_path(post_comments_path(post))

Note: You can also assert the current path by testing the value of current_path directly. However, using the have_current_path matcher is safer since it uses Capybara’s waiting behaviour to ensure that preceding actions (such as a click_link) have completed.


Full reference: Capybara::Node::Actions

You can interact with the webapp by following links and buttons. Capybara automatically follows any redirects, and submits forms associated with buttons.

click_link('id-of-link')
click_link('Link Text')
click_button('Save')
click_on('Link Text') # clicks on either links or buttons
click_on('Button Value')

Interacting with forms

Full reference: Capybara::Node::Actions

There are a number of tools for interacting with form elements:

fill_in('First Name', with: 'John')
fill_in('Password', with: 'Seekrit')
fill_in('Description', with: 'Really Long Text...')
choose('A Radio Button')
check('A Checkbox')
uncheck('A Checkbox')
attach_file('Image', '/path/to/image.jpg')
select('Option', from: 'Select Box')

Querying

Full reference: Capybara::Node::Matchers

Capybara has a rich set of options for querying the page for the existence of certain elements, and working with and manipulating those elements.

page.has_selector?('table tr')
page.has_selector?(:xpath, './/table/tr')

page.has_xpath?('.//table/tr')
page.has_css?('table tr.foo')
page.has_content?('foo')

Note: The negative forms like has_no_selector? are different from not has_selector?. Read the section on asynchronous JavaScript for an explanation.

You can use these with RSpec’s magic matchers:

expect(page).to have_selector('table tr')
expect(page).to have_selector(:xpath, './/table/tr')

expect(page).to have_xpath('.//table/tr')
expect(page).to have_css('table tr.foo')
expect(page).to have_content('foo')

Finding

Full reference: Capybara::Node::Finders

You can also find specific elements, in order to manipulate them:

find_field('First Name').value
find_field(id: 'my_field').value
find_link('Hello', :visible => :all).visible?
find_link(class: ['some_class', 'some_other_class'], :visible => :all).visible?

find_button('Send').click
find_button(value: '1234').click

find(:xpath, ".//table/tr").click
find("#overlay").find("h1").click
all('a').each { |a| a[:href] }

If you need to find elements by additional attributes/properties you can also pass a filter block, which will be checked inside the normal waiting behavior. If you find yourself needing to use this a lot you may be better off adding a custom selector or adding a filter to an existing selector.

find_field('First Name'){ |el| el['data-xyz'] == '123' }
find("#img_loading"){ |img| img['complete'] == true }

Note: find will wait for an element to appear on the page, as explained in the Ajax section. If the element does not appear it will raise an error.

These elements all have all the Capybara DSL methods available, so you can restrict them to specific parts of the page:

find('#navigation').click_link('Home')
expect(find('#navigation')).to have_button('Sign out')

Scoping

Capybara makes it possible to restrict certain actions, such as interacting with forms or clicking links and buttons, to within a specific area of the page. For this purpose you can use the generic within method. Optionally you can specify which kind of selector to use.

within("li#employee") do
  fill_in 'Name', with: 'Jimmy'
end

within(:xpath, ".//li[@id='employee']") do
  fill_in 'Name', with: 'Jimmy'
end

There are special methods for restricting the scope to a specific fieldset, identified by either an id or the text of the fieldset’s legend tag, and to a specific table, identified by either id or text of the table’s caption tag.

within_fieldset('Employee') do
  fill_in 'Name', with: 'Jimmy'
end

within_table('Employee') do
  fill_in 'Name', with: 'Jimmy'
end

Working with windows

Capybara provides some methods to ease finding and switching windows:

facebook_window = window_opened_by do
  click_button 'Like'
end
within_window facebook_window do
  find('#login_email').set('a@example.com')
  find('#login_password').set('qwerty')
  click_button 'Submit'
end

Scripting

In drivers which support it, you can easily execute JavaScript:

    page.execute_script("$('body').empty()")

For simple expressions, you can return the result of the script. Note that this may break with more complicated expressions:

    result = page.evaluate_script('4 + 4');

Modals

In drivers which support it, you can accept, dismiss and respond to alerts, confirms and prompts.

You can accept or dismiss alert messages by wrapping the code that produces an alert in a block:

accept_alert do
  click_link('Show Alert')
end

You can accept or dismiss a confirmation by wrapping it in a block, as well:

dismiss_confirm do
  click_link('Show Confirm')
end

You can accept or dismiss prompts as well, and also provide text to fill in for the response:

accept_prompt(with: 'Linus Torvalds') do
  click_link('Show Prompt About Linux')
end

All modal methods return the message that was presented. So, you can access the prompt message by assigning the return to a variable:

message = accept_prompt(with: 'Linus Torvalds') do
  click_link('Show Prompt About Linux')
end
expect(message).to eq('Who is the chief architect of Linux?')

Debugging

It can be useful to take a snapshot of the page as it currently is and take a look at it:

    save_and_open_page

You can also retrieve the current state of the DOM as a string using page.html.

    print page.html

This is mostly useful for debugging. You should avoid testing against the contents of page.html and use the more expressive finder methods instead.

Finally, in drivers that support it, you can save a screenshot:

    page.save_screenshot('screenshot.png')

Or have it save and automatically open:

    save_and_open_screenshot

Screenshots are saved to Capybara.save_path, relative to the app directory. If you have required capybara/rails, Capybara.save_path will default to tmp/capybara.


Asynchronous JavaScript (Ajax and friends)

When working with asynchronous JavaScript, you might come across situations where you are attempting to interact with an element which is not yet present on the page. Capybara automatically deals with this by waiting for elements to appear on the page.

When issuing instructions to the DSL such as:

click_link('foo')
click_link('bar')
expect(page).to have_content('baz')

If clicking on the foo link triggers an asynchronous process, such as an Ajax request, which, when complete will add the bar link to the page, clicking on the bar link would be expected to fail, since that link doesn’t exist yet. However Capybara is smart enough to retry finding the link for a brief period of time before giving up and throwing an error. The same is true of the next line, which looks for the content baz on the page; it will retry looking for that content for a brief time. You can adjust how long this period is (the default is 2 seconds):

    Capybara.default_max_wait_time = 5

Be aware that because of this behaviour, the following two statements are not equivalent, and you should always use the latter!

!page.has_xpath?('a')
page.has_no_xpath?('a')

The former would immediately fail because the content has not yet been removed. Only the latter would wait for the asynchronous process to remove the content from the page.

Capybara’s RSpec matchers, however, are smart enough to handle either form. The two following statements are functionally equivalent:

expect(page).not_to have_xpath('a')
expect(page).to have_no_xpath('a')

Capybara’s waiting behaviour is quite advanced, and can deal with situations such as the following line of code:

expect(find('#sidebar').find('h1')).to have_content('Something')

Even if JavaScript causes #sidebar to disappear off the page, Capybara will automatically reload it and any elements it contains. So if an AJAX request causes the contents of #sidebar to change, which would update the text of the h1 to “Something”, and this happened, this test would pass. If you do not want this behaviour, you can set Capybara.automatic_reload to false.


XPath, CSS and selectors

Capybara does not try to guess what kind of selector you are going to give it, and will always use CSS by default. If you want to use XPath, you’ll need to do:

within(:xpath, './/ul/li') { ... }
find(:xpath, './/ul/li').text
find(:xpath, './/li[contains(.//a[@href = "#"]/text(), "foo")]').value

Alternatively you can set the default selector to XPath:

Capybara.default_selector = :xpath
find('.//ul/li').text

Capybara allows you to add custom selectors, which can be very useful if you find yourself using the same kinds of selectors very often:

Capybara.add_selector(:id) do
  xpath { |id| XPath.descendant[XPath.attr(:id) == id.to_s] }
end

Capybara.add_selector(:row) do
  xpath { |num| ".//tbody/tr[#{num}]" }
end

Capybara.add_selector(:flash_type) do
  css { |type| "#flash.#{type}" }
end

The block given to xpath must always return an XPath expression as a String, or an XPath expression generated through the XPath gem. You can now use these selectors like this:

find(:id, 'post_123')
find(:row, 3)
find(:flash_type, :notice)

Beware the XPath // trap

In XPath the expression // means something very specific, and it might not be what you think. Contrary to common belief, // means “anywhere in the document” not “anywhere in the current context”. As an example:

page.find(:xpath, '//body').all(:xpath, '//script')

You might expect this to find all script tags in the body, but actually, it finds all script tags in the entire document, not only those in the body! What you’re looking for is the .// expression which means “any descendant of the current node”:

page.find(:xpath, '//body').all(:xpath, './/script')

Note: 这个其实是不是陷阱的陷阱吧,讲道理一般使用xpath写法估计如下,这个知识点算是聊胜于无了.

all(:xpath,"//body/script")[2]

The same thing goes for within:

within(:xpath, '//body') do
  page.find(:xpath, './/script')
  within(:xpath, './/table/tbody') do
  ...
  end
end

小技巧

Capybara.current_driver = Capybara.javascript_driver
# some code execute
Capybara.use_default_driver
 类似资料: