Automatically locating locales from the WWW browser and testing with Cucumber

I am testing my application with Cucumber, and it worked before I added automatic locale detection from the WWW browser to application_controller.rb:

  before_filter :set_locale

  private

    def set_locale
      xxx = request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
      if xxx.match /^(en|fr)$/
        I18n.locale = xxx
      else
        I18n.locale = 'en'
      end
    end

I have a script:

  Scenario: Successful sign up
    Given I am an anonymous user
    And I am on the home page
    When ...

When I start the cucumber , I get an error message:

Given I am an anonymous user                   # features/step_definitions/user_steps.rb:7
And I am on the home page                      # features/step_definitions/webrat_steps.rb:6
  private method `scan' called for nil:NilClass (NoMethodError)
  C:/workspace/jeengle/app/controllers/application_controller.rb:33:in `set_locale'
  c:/worktools/ruby/lib/ruby/1.8/benchmark.rb:308:in `realtime'
  (eval):2:in `/^I am on (.+)$/'
  features/manage_users.feature:8:in `And I am on the home page'

I tried to do this in the instructions before in the step_definitions folder:

Before do
  request.env['HTTP_ACCEPT_LANGUAGE'] = "en"
end

but I have one more error:

  undefined method `env' for nil:NilClass (NoMethodError)

Does anyone know how to initialize / emulate request.env ['HTTP_ACCEPT_LANGUAGE'] in a cucumber?


UPDATED

The cucumber test passed when I rewrote the set_locale method :

  xxx = request.env['HTTP_ACCEPT_LANGUAGE']    
  if xxx
    xxx = xxx.scan(/^[a-z]{2}/).first
    if xxx.match /^(en|ru)$/
      I18n.locale = xxx
  end
  else
    I18n.locale = 'en'
  end

This is not a solution, but it works.

+3
2

Webrat, Cucumber. ()

  • .
  • " " , Webrat,
  • Webrat
  • , "Accept-Language"

- Webrat , . , Webrat : "header", .

, , , , :

Given /^an Accept Language header$/ do
  header "Accept-Language", "en;en-us" # or whatever value you need for testing
end`

, , Webrat .

btw Rspec, , BDD .

+4

- " , ". :

Before do
  header 'Accept-Language', 'en-US' 
end

, .

+2

Source: https://habr.com/ru/post/1726193/


All Articles