How to raise test project on windows 10 (Cucumber + capybara + selenium-webdriver)

The article is intended for familiarity with auto-testing and scanning of the environment in Windows 10 and is intended for those who know just a little about Cucumber + Capybara + Selenium-webdriver . The idea for the article came about because of the differences in deploying the environment on Windows 10 and Linux.


A few words about gem-ah (libraries) Cucumber + Capybara + Selenium-webdriver, which are needed to run and fill UI tests with tests.

Cucumber


Сucumber is a heme that allows writing tests in human language. To do this, use the Gherkin notation, which defines the structure and rules for writing scripts. You can read in detail here.


Capybara


Capybara - heme, allowing you to search / click / ... on the elements of the browser. Those. It is a link between the Cucumber steps (steps) of the test, and the webdriver (an instance of the browser being called). Here you can look at the methods of this heme.

Selenium-webdriver


Selenium-webdriver is a tool to automate web browser actions. Essentially, this is an instance of the browser instance.

Preliminary actions


Description of preliminary actions
Для удобства демонстрации будем использовать RubyMine. Можно скачать пробную версию на 30 дней.

Скачиваем Firefox и Хром для запуска тестов.

Скачиваем и устанавливаем Git (система управления версиями или аналоичная VCS, оффициальный сайт). Но Git нужен когда у Вас уже есть проект или вы хотите хранить свой код в Git системе.

So, let's begin


We already have RubyMine installed.

  1. You need to install the Ruby language itself. To do this, go here and put RubyInstaller. I chose the latest release (RubyInstaller 2.5.1-2) with the DevKit package. Through this setup package, you can run tests from the console, as in Linux, as well as flexibly manage gems.
  2. The RubyInstaller package is installed and we proceed to the configuration.
    If we want to create a new project, then open RubyMine and create an empty project, specifying the installed Ruby.

  3. Next, we need to create just such a folder and file structure according to the annotation


    Described in detail here
  4. Gemfile - contains a list of gems that are used in the project

    Here are the contents of our gemfile, with the most basic gems for UI tests.
    source 'https://rubygems.org'
    gem 'cucumber'
    gem 'capybara'
    gem 'selenium-webdriver'
    gem 'chromedriver-helper' 


    These 4 gems must be specified in the gemfile.
    gem 'chromedriver-helper' is a chrome driver that allows you to run testers on Chrome.
    With the help of this Gemfile you need to install our favorite gems. It is easiest to install on Windows from the RubyMine interface: Tools -> Bundler -> Install menu . A bundler is also a gem, but serves to control gems. But it can also be done from the command line, which is located in the program menu under the name Start Command Prompt ...
    By the way, with the help of this command line, you can also run tests bypassing RubyMine.
  5. The env.rb file is a key rb file for running UI tests. When initializing variables and test files, env.rb will be the very first. It registers the browser on which the testers will run. Ready example env.rb, where the registration of Chrome, Firefox, or make it clear that we do not need a browser at all to run the tests.
    Cases when a browser is not needed - we check rest requests, integration testing, although it is considered that Cucumber tests are not quite suitable for this.

    Writing env.rb
    require'capybara/cucumber'require'selenium-webdriver'
    Capybara.register_driver :driverdo|app|case ENV['DRIVER']
        when'chrome'
          Capybara::Selenium::Driver.new(app, :browser => :chrome)
        when'without_browser'
          Capybara.default_driver = :mechanizeelse
          client  = Selenium::WebDriver::Remote::Http::Default.new
          Capybara::Selenium::Driver.new(app, :browser => :firefox, port:10000 + Random.rand(1000), http_client: client)
        endend
    Capybara.default_driver   = :driver
    Capybara.default_selector = :xpath


    Also, here you need to mention the issue of versioning Firefox.
    If you have Firefox version 46 or lower installed, then to run the tests correctly, you need gem 'capybara' version '2.53.4' or lower.

    If the Firefox version is higher than 46, then it works according to other principles based on “geckodriver” and therefore you need to install a geckodriver in order to run the test correctly .

    A tour of the reasons for what you need geckodriver
    До версии 47 версии драйвер автоматизации Firefox был всего лишь расширением, которое включалось в каждый клиент. Но это расширение было удалено из-за изменения политики, требющей теперь, чтобы все расширения подписывались Mozilla.

    Marionette — это новый драйвер, который поставляется вместе с Firefox. У этого драйвера есть собственный протокол, который несовместим с протоколом Selenium/WebDriver.

    Geckodriver — это сервер приложений, реализующий протокол Selenium/WebDriver. Он переводит команды Selenium и перенаправляет их в драйвер Marionette.

    An important nuance , after installing “geckodriver”, it is necessary to prescribe system paths in order for our “geckodriver” to be found when executing env.rb.

    system paths


  6. Then you just have to write a test test and run it on Chrome, Firefox and without a browser :). For example, we will write several steps to enter mail.ru mail.

    Description of steps
    # encoding: UTF-8# language: ru
    Given(/^Переходим на страницу "(.*?)"$/) do|page|
      visit page
    end
    Given(/^Вводим текст "(.*?)" в поле c id "(.*?)"$/) do|text, field_id|
      find("//input[@id='#{field_id}']").set(text)
    end
    Given(/^Выбираем текст "(.*?)" в выпадающем списке с id "(.*?)"$/) do|text, select_id|
      find("//select[@id='#{select_id}']/option[text()='#{text}']").click
    end
    Given(/^Нажимаем кнопку с текстом "(.*?)"$/) do|text|
      find("//input[@value='#{text}']").click
    end
    Given(/^Ожидаем (\d+) секунд(?:|ы)$/) do|sec|
      sleep sec.to_i
    end


  7. And also the cucumber test itself

    test.feature
    # encoding: UTF-8# language: ru
    Функция: Открываем почту
      Сценарий: Открываем почту
        Дано Переходим на страницу "https://mail.ru/"
        И Вводим текст "dorian.grey.2019" в поле c id"mailbox:login"
        И Вводим текст "********" в поле c id"mailbox:password"
        Когда Выбираем текст "@inbox.ru" в выпадающем списке с id"mailbox:domain"
        Тогда Нажимаем кнопку с текстом "Войти"
        И Ожидаем 5 секунд


  8. It remains only to check all our efforts and enjoy the success of the UI tests (in example 1 test) :). Remained the last setting - setting run tests. Go to the RubyMine menu -> Edit Configurations -> Runner Options - here we make the driver selection :)
    ENV ['DRIVER'] from env.rb is the launch setting. And we just need to specify in the Runner Options "DRIVER = firefox" or "DRIVER = chrome".

Launch,



That's all, successful Cucumber tests!

Also popular now: