Best Capybara code snippet using Capybara.config
capybara.rb
Source:capybara.rb
2require 'timeout'3require 'nokogiri'4require 'xpath'5require 'forwardable'6require 'capybara/config'7module Capybara8 class CapybaraError < StandardError; end9 class DriverNotFoundError < CapybaraError; end10 class FrozenInTime < CapybaraError; end11 class ElementNotFound < CapybaraError; end12 class ModalNotFound < CapybaraError; end13 class Ambiguous < ElementNotFound; end14 class ExpectationNotMet < ElementNotFound; end15 class FileNotFound < CapybaraError; end16 class UnselectNotAllowed < CapybaraError; end17 class NotSupportedByDriverError < CapybaraError; end18 class InfiniteRedirectError < CapybaraError; end19 class ScopeError < CapybaraError; end20 class WindowError < CapybaraError; end21 class ReadOnlyElementError < CapybaraError; end22 class << self23 extend Forwardable24 # DelegateCapybara global configurations25 # @!method app26 # See {Capybara.configure}27 # @!method reuse_server28 # See {Capybara.configure}29 # @!method threadsafe30 # See {Capybara.configure}31 # @!method server32 # See {Capybara.configure}33 # @!method default_driver34 # See {Capybara.configure}35 # @!method javascript_driver36 # See {Capybara.configure}37 # @!method allow_gumbo38 # See {Capybara.configure}39 Config::OPTIONS.each do |method|40 def_delegators :config, method, "#{method}="41 end42 # Delegate Capybara global configurations43 # @!method default_selector44 # See {Capybara.configure}45 # @!method default_max_wait_time46 # See {Capybara.configure}47 # @!method app_host48 # See {Capybara.configure}49 # @!method always_include_port50 # See {Capybara.configure}51 SessionConfig::OPTIONS.each do |method|52 def_delegators :config, method, "#{method}="53 end54 ##55 #56 # Configure Capybara to suit your needs.57 #58 # Capybara.configure do |config|59 # config.run_server = false60 # config.app_host = 'http://www.google.com'61 # end62 #63 # #### Configurable options64 #65 # - **allow_gumbo** (Boolean = `false`) - When `nokogumbo` is available, whether it will be used to parse HTML strings.66 # - **always_include_port** (Boolean = `false`) - Whether the Rack server's port should automatically be inserted into every visited URL67 # unless another port is explicitly specified.68 # - **app_host** (String, `nil`) - The default host to use when giving a relative URL to visit, must be a valid URL e.g. `http://www.example.com`.69 # - **asset_host** (String = `nil`) - Where dynamic assets are hosted - will be prepended to relative asset locations if present.70 # - **automatic_label_click** (Boolean = `false`) - Whether {Capybara::Node::Element#choose Element#choose}, {Capybara::Node::Element#check Element#check},71 # {Capybara::Node::Element#uncheck Element#uncheck} will attempt to click the associated `<label>` element if the checkbox/radio button are non-visible.72 # - **automatic_reload** (Boolean = `true`) - Whether to automatically reload elements as Capybara is waiting.73 # - **default_max_wait_time** (Numeric = `2`) - The maximum number of seconds to wait for asynchronous processes to finish.74 # - **default_normalize_ws** (Boolean = `false`) - Whether text predicates and matchers use normalize whitespace behavior.75 # - **default_selector** (`:css`, `:xpath` = `:css`) - Methods which take a selector use the given type by default. See also {Capybara::Selector}.76 # - **default_set_options** (Hash = `{}`) - The default options passed to {Capybara::Node::Element#set Element#set}.77 # - **enable_aria_label** (Boolean = `false`) - Whether fields, links, and buttons will match against `aria-label` attribute.78 # - **exact** (Boolean = `false`) - Whether locators are matched exactly or with substrings. Only affects selector conditions79 # written using the `XPath#is` method.80 # - **exact_text** (Boolean = `false`) - Whether the text matchers and `:text` filter match exactly or on substrings.81 # - **ignore_hidden_elements** (Boolean = `true`) - Whether to ignore hidden elements on the page.82 # - **match** (`:one`, `:first`, `:prefer_exact`, `:smart` = `:smart`) - The matching strategy to find nodes.83 # - **predicates_wait** (Boolean = `true`) - Whether Capybara's predicate matchers use waiting behavior by default.84 # - **raise_server_errors** (Boolean = `true`) - Should errors raised in the server be raised in the tests?85 # - **reuse_server** (Boolean = `true`) - Whether to reuse the server thread between multiple sessions using the same app object.86 # - **run_server** (Boolean = `true`) - Whether to start a Rack server for the given Rack app.87 # - **save_path** (String = `Dir.pwd`) - Where to put pages saved through {Capybara::Session#save_page save_page}, {Capybara::Session#save_screenshot save_screenshot},88 # {Capybara::Session#save_and_open_page save_and_open_page}, or {Capybara::Session#save_and_open_screenshot save_and_open_screenshot}.89 # - **server** (Symbol = `:default` (which uses puma)) - The name of the registered server to use when running the app under test.90 # - **server_errors** (Array\<Class> = `[Exception]`) - Error classes that should be raised in the tests if they are raised in the server91 # and {configure raise_server_errors} is `true`.92 # - **test_id** (Symbol, String, `nil` = `nil`) - Optional attribute to match locator against with built-in selectors along with id.93 # - **threadsafe** (Boolean = `false`) - Whether sessions can be configured individually.94 # - **w3c_click_offset** (Boolean = 'false') - Whether click offsets should be from element center (true) or top left (false)95 #96 # #### DSL Options97 #98 # When using `capybara/dsl`, the following options are also available:99 #100 # - **default_driver** (Symbol = `:rack_test`) - The name of the driver to use by default.101 # - **javascript_driver** (Symbol = `:selenium`) - The name of a driver to use for JavaScript enabled tests.102 #103 def configure104 yield config105 end106 ##107 #108 # Register a new driver for Capybara.109 #110 # Capybara.register_driver :rack_test do |app|111 # Capybara::RackTest::Driver.new(app)112 # end113 #114 # @param [Symbol] name The name of the new driver115 # @yield [app] This block takes a rack app and returns a Capybara driver116 # @yieldparam [<Rack>] app The rack application that this driver runs against. May be nil.117 # @yieldreturn [Capybara::Driver::Base] A Capybara driver instance118 #119 def register_driver(name, &block)120 drivers[name] = block121 end122 ##123 #124 # Register a new server for Capybara.125 #126 # Capybara.register_server :webrick do |app, port, host|127 # require 'rack/handler/webrick'128 # Rack::Handler::WEBrick.run(app, ...)129 # end130 #131 # @param [Symbol] name The name of the new driver132 # @yield [app, port, host] This block takes a rack app and a port and returns a rack server listening on that port133 # @yieldparam [<Rack>] app The rack application that this server will contain.134 # @yieldparam port The port number the server should listen on135 # @yieldparam host The host/ip to bind to136 #137 def register_server(name, &block)138 servers[name.to_sym] = block139 end140 ##141 #142 # Add a new selector to Capybara. Selectors can be used by various methods in Capybara143 # to find certain elements on the page in a more convenient way. For example adding a144 # selector to find certain table rows might look like this:145 #146 # Capybara.add_selector(:row) do147 # xpath { |num| ".//tbody/tr[#{num}]" }148 # end149 #150 # This makes it possible to use this selector in a variety of ways:151 #152 # find(:row, 3)153 # page.find('table#myTable').find(:row, 3).text154 # page.find('table#myTable').has_selector?(:row, 3)155 # within(:row, 3) { expect(page).to have_content('$100.000') }156 #157 # Here is another example:158 #159 # Capybara.add_selector(:id) do160 # xpath { |id| XPath.descendant[XPath.attr(:id) == id.to_s] }161 # end162 #163 # Note that this particular selector already ships with Capybara.164 #165 # @param [Symbol] name The name of the selector to add166 # @yield A block executed in the context of the new {Capybara::Selector}167 #168 def add_selector(name, **options, &block)169 Capybara::Selector.add(name, **options, &block)170 end171 ##172 #173 # Modify a selector previously created by {Capybara.add_selector}.174 # For example, adding a new filter to the :button selector to filter based on175 # button style (a class) might look like this176 #177 # Capybara.modify_selector(:button) do178 # filter (:btn_style, valid_values: [:primary, :secondary]) { |node, style| node[:class].split.include? "btn-#{style}" }179 # end180 #181 #182 # @param [Symbol] name The name of the selector to modify183 # @yield A block executed in the context of the existing {Capybara::Selector}184 #185 def modify_selector(name, &block)186 Capybara::Selector.update(name, &block)187 end188 def drivers189 @drivers ||= {}190 end191 def servers192 @servers ||= {}193 end194 # Wraps the given string, which should contain an HTML document or fragment195 # in a {Capybara::Node::Simple} which exposes all {Capybara::Node::Matchers},196 # {Capybara::Node::Finders} and {Capybara::Node::DocumentMatchers}. This allows you to query197 # any string containing HTML in the exact same way you would query the current document in a Capybara198 # session.199 #200 # @example A single element201 # node = Capybara.string('<a href="foo">bar</a>')202 # anchor = node.first('a')203 # anchor[:href] #=> 'foo'204 # anchor.text #=> 'bar'205 #206 # @example Multiple elements207 # node = Capybara.string <<-HTML208 # <ul>209 # <li id="home">Home</li>210 # <li id="projects">Projects</li>211 # </ul>212 # HTML213 #214 # node.find('#projects').text # => 'Projects'215 # node.has_selector?('li#home', text: 'Home')216 # node.has_selector?('#projects')217 # node.find('ul').find('li:first-child').text # => 'Home'218 #219 # @param [String] html An html fragment or document220 # @return [Capybara::Node::Simple] A node which has Capybara's finders and matchers221 #222 def string(html)223 Capybara::Node::Simple.new(html)224 end225 ##226 #227 # Runs Capybara's default server for the given application and port228 # under most circumstances you should not have to call this method229 # manually.230 #231 # @param [Rack Application] app The rack application to run232 # @param [Integer] port The port to run the application on233 #234 def run_default_server(app, port)235 servers[:puma].call(app, port, server_host)236 end237 ##238 #239 # @return [Symbol] The name of the driver currently in use240 #241 def current_driver242 if threadsafe243 Thread.current['capybara_current_driver']244 else245 @current_driver246 end || default_driver247 end248 alias_method :mode, :current_driver249 def current_driver=(name)250 if threadsafe251 Thread.current['capybara_current_driver'] = name252 else253 @current_driver = name254 end255 end256 ##257 #258 # Use the default driver as the current driver259 #260 def use_default_driver261 self.current_driver = nil262 end263 ##264 #265 # Yield a block using a specific driver266 #267 def using_driver(driver)268 previous_driver = Capybara.current_driver269 Capybara.current_driver = driver270 yield271 ensure272 self.current_driver = previous_driver273 end274 ##275 #276 # Yield a block using a specific wait time277 #278 def using_wait_time(seconds)279 previous_wait_time = Capybara.default_max_wait_time280 Capybara.default_max_wait_time = seconds281 yield282 ensure283 Capybara.default_max_wait_time = previous_wait_time284 end285 ##286 #287 # The current {Capybara::Session} based on what is set as {app} and {current_driver}.288 #289 # @return [Capybara::Session] The currently used session290 #291 def current_session292 specified_session || session_pool["#{current_driver}:#{session_name}:#{app.object_id}"]293 end294 ##295 #296 # Reset sessions, cleaning out the pool of sessions. This will remove any session information such297 # as cookies.298 #299 def reset_sessions!300 # reset in reverse so sessions that started servers are reset last301 session_pool.reverse_each { |_mode, session| session.reset! }302 end303 alias_method :reset!, :reset_sessions!304 ##305 #306 # The current session name.307 #308 # @return [Symbol] The name of the currently used session.309 #310 def session_name311 if threadsafe312 Thread.current['capybara_session_name'] ||= :default313 else314 @session_name ||= :default315 end316 end317 def session_name=(name)318 if threadsafe319 Thread.current['capybara_session_name'] = name320 else321 @session_name = name322 end323 end324 ##325 #326 # Yield a block using a specific session name or {Capybara::Session} instance.327 #328 def using_session(name_or_session)329 previous_session_info = {330 specified_session: specified_session,331 session_name: session_name,332 current_driver: current_driver,333 app: app334 }335 self.specified_session = self.session_name = nil336 if name_or_session.is_a? Capybara::Session337 self.specified_session = name_or_session338 else339 self.session_name = name_or_session340 end341 yield342 ensure343 self.session_name, self.specified_session = previous_session_info.values_at(:session_name, :specified_session)344 self.current_driver, self.app = previous_session_info.values_at(:current_driver, :app) if threadsafe345 end346 ##347 #348 # Parse raw html into a document using Nokogiri, and adjust textarea contents as defined by the spec.349 #350 # @param [String] html The raw html351 # @return [Nokogiri::HTML::Document] HTML document352 #353 def HTML(html) # rubocop:disable Naming/MethodName354 if Nokogiri.respond_to?(:HTML5) && Capybara.allow_gumbo # Nokogumbo installed and allowed for use355 Nokogiri::HTML5(html).tap do |document|356 document.xpath('//template').each do |template|357 # template elements content is not part of the document358 template.inner_html = ''359 end360 document.xpath('//textarea').each do |textarea|361 # The Nokogumbo HTML5 parser already returns spec compliant contents362 textarea['_capybara_raw_value'] = textarea.content363 end364 end365 else366 Nokogiri::HTML(html).tap do |document|367 document.xpath('//template').each do |template|368 # template elements content is not part of the document369 template.inner_html = ''370 end371 document.xpath('//textarea').each do |textarea|372 textarea['_capybara_raw_value'] = textarea.content.sub(/\A\n/, '')373 end374 end375 end376 end377 def session_options378 config.session_options379 end380 private381 def config382 @config ||= Capybara::Config.new383 end384 def session_pool385 @session_pool ||= Hash.new do |hash, name|386 hash[name] = Capybara::Session.new(current_driver, app)387 end388 end389 def specified_session390 if threadsafe391 Thread.current['capybara_specified_session']392 else393 @specified_session ||= nil394 end395 end396 def specified_session=(session)397 if threadsafe398 Thread.current['capybara_specified_session'] = session399 else400 @specified_session = session401 end402 end403 end404 self.default_driver = nil405 self.current_driver = nil406 self.server_host = nil407 module Driver; end408 module RackTest; end409 module Selenium; end410 require 'capybara/helpers'411 require 'capybara/session'412 require 'capybara/window'413 require 'capybara/server'414 require 'capybara/selector'415 require 'capybara/result'416 require 'capybara/version'417 require 'capybara/queries/base_query'418 require 'capybara/queries/selector_query'419 require 'capybara/queries/text_query'420 require 'capybara/queries/title_query'421 require 'capybara/queries/current_path_query'422 require 'capybara/queries/match_query'423 require 'capybara/queries/ancestor_query'424 require 'capybara/queries/sibling_query'425 require 'capybara/queries/style_query'426 require 'capybara/node/finders'427 require 'capybara/node/matchers'428 require 'capybara/node/actions'429 require 'capybara/node/document_matchers'430 require 'capybara/node/simple'431 require 'capybara/node/base'432 require 'capybara/node/element'433 require 'capybara/node/document'434 require 'capybara/driver/base'435 require 'capybara/driver/node'436 require 'capybara/rack_test/driver'437 require 'capybara/rack_test/node'438 require 'capybara/rack_test/form'439 require 'capybara/rack_test/browser'440 require 'capybara/rack_test/css_handlers.rb'441 require 'capybara/selenium/node'442 require 'capybara/selenium/driver'443end444require 'capybara/registrations/servers'445require 'capybara/registrations/drivers'446Capybara.configure do |config|447 config.always_include_port = false448 config.run_server = true449 config.server = :default450 config.default_selector = :css451 config.default_max_wait_time = 2452 config.ignore_hidden_elements = true453 config.default_host = 'http://www.example.com'454 config.automatic_reload = true455 config.match = :smart456 config.exact = false457 config.exact_text = false458 config.raise_server_errors = true459 config.server_errors = [Exception]460 config.visible_text_only = false461 config.automatic_label_click = false462 config.enable_aria_label = false463 config.reuse_server = true464 config.default_set_options = {}465 config.test_id = nil466 config.predicates_wait = true467 config.default_normalize_ws = false468 config.allow_gumbo = false469 config.w3c_click_offset = false470end...
per_session_config_spec.rb
Source:per_session_config_spec.rb
...10 default_selector default_max_wait_time ignore_hidden_elements11 automatic_reload match exact raise_server_errors visible_text_only12 automatic_label_click enable_aria_label save_path13 asset_host].each do |m|14 expect(session.config.public_send(m)).to eq Capybara.public_send(m)15 end16 end17 it "doesn't change global session when changed" do18 Capybara.threadsafe = true19 host = 'http://my.example.com'20 session = Capybara::Session.new(:rack_test, TestApp) do |config|21 config.default_host = host22 config.automatic_label_click = !config.automatic_label_click23 config.server_errors << ArgumentError24 end25 expect(Capybara.default_host).not_to eq host26 expect(session.config.default_host).to eq host27 expect(Capybara.automatic_label_click).not_to eq session.config.automatic_label_click28 expect(Capybara.server_errors).not_to eq session.config.server_errors29 end30 it "doesn't allow session configuration block when false" do31 Capybara.threadsafe = false32 expect do33 Capybara::Session.new(:rack_test, TestApp) { |config| }34 end.to raise_error 'A configuration block is only accepted when Capybara.threadsafe == true'35 end36 it "doesn't allow session config when false" do37 Capybara.threadsafe = false38 session = Capybara::Session.new(:rack_test, TestApp)39 expect { session.config.default_selector = :title }.to raise_error(/Per session settings are only supported when Capybara.threadsafe == true/)40 expect do41 session.configure do |config|42 config.exact = true43 end44 end.to raise_error(/Session configuration is only supported when Capybara.threadsafe == true/)45 end46 it 'uses the config from the session' do47 Capybara.threadsafe = true48 session = Capybara::Session.new(:rack_test, TestApp) do |config|49 config.default_selector = :link50 end51 session.visit('/with_html')52 expect(session.find('foo').tag_name).to eq 'a'53 end54 it "won't change threadsafe once a session is created" do55 Capybara.threadsafe = true56 Capybara.threadsafe = false57 Capybara::Session.new(:rack_test, TestApp)58 expect { Capybara.threadsafe = true }.to raise_error(/Threadsafe setting cannot be changed once a session is created/)59 end60 end61end...
config
Using AI Code Generation
1 Capybara::Poltergeist::Driver.new(app, {:js_errors => false})2 Capybara::Poltergeist::Driver.new(app, {:js_errors => false})3 Capybara::Poltergeist::Driver.new(app, {:js_errors => false})
config
Using AI Code Generation
1 def search_for(query)2World(MyModule)3When(/^I search for "(.*?)"$/) do |query|4 search_for(query)5Then(/^I should see "(.*?)"$/) do |text|6 page.should have_content(text)7 def search_for(query)8World(MyModule)9When(/^I search for "(.*?)"$/) do |query|10 search_for(query)11Then(/^I should see "(.*?)"$/) do |text|12 page.should have_content(text)13 def search_for(query)14World(MyModule)15When(/^I search for "(.*?)"$/) do |query|16 search_for(query)17Then(/^I should see "(.*?)"$/) do |
config
Using AI Code Generation
1 Capybara::Selenium::Driver.new(app, :browser => :chrome)2 Capybara::Selenium::Driver.new(app, :browser => :chrome)3 Capybara::Selenium::Driver.new(app, :browser => :chrome)4 Capybara::Selenium::Driver.new(app, :browser => :chrome)
config
Using AI Code Generation
1 Capybara::Selenium::Driver.new(app, :browser => :chrome)2World(Capybara::DSL)3 Capybara::Selenium::Driver.new(app, :browser => :chrome)4World(Capybara::DSL)5 Capybara::Selenium::Driver.new(app, :browser => :chrome)6World(Capybara::DSL)7 Capybara::Selenium::Driver.new(app, :browser => :chrome)8World(Capybara::DSL)
config
Using AI Code Generation
1visit('http://www.google.com')2fill_in('q', with: 'Hello World')3click_button('Google Search')4 Capybara::Selenium::Driver.new(app, browser: :chrome)5visit('http://www.google.com')6fill_in('q', with: 'Hello World')7click_button('Google Search')8 Capybara::Selenium::Driver.new(app, browser: :chrome)9visit('http://www.google.com')10fill_in('q', with: 'Hello World')11click_button('Google Search')12 Capybara::Selenium::Driver.new(app, browser: :chrome)13visit('http://www.google.com')14fill_in('q', with: 'Hello World')15click_button('Google Search')
config
Using AI Code Generation
1 visit('/')2 def search_for(query)3 fill_in('q', :with => query)4 click_button('Google Search')5google.search_for('Capybara')6 Capybara::Selenium::Driver.new(app, :browser => :chrome)7session = Capybara::Session.new(:selenium)8session.visit('https://www.google.com')9session.fill_in('q', :with => 'Capybara')10session.click_button('Google Search')11 Capybara::Selenium::Driver.new(app, :browser => :firefox)12session = Capybara::Session.new(:selenium)13session.visit('https://www.google.com')14session.fill_in('q', :with => 'Capybara')15session.click_button('Google Search')16 Capybara::Selenium::Driver.new(app, :browser => :firefox17 Capybara::Selenium::Driver.new(app, :browser => :chrome)18 Capybara::Selenium::Driver.new(app, :browser => :chrome)19 Capybara::Selenium::Driver.new(app, :browser => :chrome)20 Capybara::Selenium::Driver.new(app, :browser => :chrome)
config
Using AI Code Generation
1 Capybara::Selenium::Driver.new(app, :browser => :chrome)2World(Capybara::DSL)3 Capybara::Selenium::Driver.new(app, :browser => :chrome)4World(Capybara::DSL)5 Capybara::Selenium::Driver.new(app, :browser => :chrome)6World(Capybara::DSL)7 Capybara::Selenium::Driver.new(app, :browser => :chrome)8World(Capybara::DSL)
config
Using AI Code Generation
1visit('http://www.google.com')2fill_in('q', with: 'Hello World')3click_button('Google Search')4 Capybara::Selenium::Driver.new(app, browser: :chrome)5visit('http://www.google.com')6fill_in('q', with: 'Hello World')7click_button('Google Search')8 Capybara::Selenium::Driver.new(app, browser: :chrome)9visit('http://www.google.com')10fill_in('q', with: 'Hello World')11click_button('Google Search')12 Capybara::Selenium::Driver.new(app, browser: :chrome)13visit('http://www.google.com')14fill_in('q', with: 'Hello World')15click_button('Google Search')
config
Using AI Code Generation
1 visit('/')2 def search_for(query)3 fill_in('q', :with => query)4 click_button('Google Search')5google.search_for('Capybara')6 Capybara::Selenium::Driver.new(app, :browser => :chrome)7session = Capybara::Session.new(:selenium)8session.visit('https://www.google.com')9session.fill_in('q', :with => 'Capybara')10session.click_button('Google Search')11 Capybara::Selenium::Driver.new(app, :browser => :firefox)12session = Capybara::Session.new(:selenium)13session.visit('https://www.google.com')14session.fill_in('q', :with => 'Capybara')15session.click_button('Google Search')16 Capybara::Selenium::Driver.new(app, :browser => :firefox17 Capybara::Selenium::Driver.new(app, :browser => :chrome)18 Capybara::Selenium::Driver.new(app, :browser => :chrome)19 Capybara::Selenium::Driver.new(app, :browser => :chrome)
config
Using AI Code Generation
1 visit('/')2 def search_for(query)3 fill_in('q', :with => query)4 click_button('Google Search')5google.search_for('Capybara')6 Capybara::Selenium::Driver.new(app, :browser => :chrome)7session = Capybara::Session.new(:selenium)8session.visit('https://www.google.com')9session.fill_in('q', :with => 'Capybara')10session.click_button('Google Search')11 Capybara::Selenium::Driver.new(app, :browser => :firefox)12session = Capybara::Session.new(:selenium)13session.visit('https://www.google.com')14session.fill_in('q', :with => 'Capybara')15session.click_button('Google Search')16 Capybara::Selenium::Driver.new(app, :browser => :firefox
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!