2016-12-05 4 views
-1

Я довольно новичок в тесте rspec, и у меня есть проблема с попыткой проверить местоположение пользователя. Это тест, чтобы высмеять поведение country_code для блокировки спама из определенных зон.Передача переменной на тест rspec

Вот код моей службы:

class GeocodeUserAuthorizer 
    def initialize(user_country_code:) 
    @user_country_code = user_country_code 
    end 

    def authorize! 
    user_continent = ISO3166::Country.new(user_country_code).continent 

    if user_continent == 'Africa' 
     return true 
    else 
     return false 
    end 
    end 
end 

Вот код моей спецификации файла:

require 'spec_helper' 

describe GeocodeUserAuthorizer do 
    context 'with a user connecting from an authorized country' do 
    it { expect(GeocodeUserAuthorizer.new.authorize!(user_country_code: { "CA" })).to eql(true) } 
    end 
end 

А вот это код ошибки:

Failures:

1) GeocodeUserAuthorizer with a user connecting from an authorized country Failure/Error: it { expect(GeocodeUserAuthorizer.new.authorize!(user_country_code: { "CA" })).to eql(true) } ArgumentError: missing keyword: user_country_code # ./app/services/geocode_user_authorizer.rb:2:in initialize' # ./spec/services/geocode_user_authorizer_spec.rb:16:in new' # ./spec/services/geocode_user_authorizer_spec.rb:16:in block (3 levels) in <top (required)>' # ./spec/spec_helper.rb:56:in block (3 levels) in ' # ./spec/spec_helper.rb:56:in `block (2 levels) in '

Может кто-нибудь поможет?

ответ

0

Вы не назвали свой класс правильно, для вашего конструктора требуется код страны. Попробуйте это:

describe GeocodeUserAuthorizer do 
    context 'with a user connecting from an authorized country' do 
    it { expect(GeocodeUserAuthorizer.new(user_country_code: { "CA" })).authorize!).to eql(true) } 
    end 
end 

Также вы хотите добавить attr_reader для user_country_code в своем классе, если вы хотите authorize! использовать его без @ символа.

0

Хорошо, поэтому мой тест был слишком сложным и не имел разделения. Вот окончательная версия, которая работает.

Тест:

require 'spec_helper' 

describe GeocodeUserAuthorizer do 
    let(:geocode_authorizer) { GeocodeUserAuthorizer.new(country_code: country_code) } 

    context 'with a user connecting from an unauthorized country' do 
    let!(:country_code) { 'AO' } 

    it { expect(geocode_authorizer.authorize!).to eql(false) } 
    end 

    context 'with a user connecting from an authorized country' do 
    let!(:country_code) { 'CA' } 

    it { expect(geocode_authorizer.authorize!).to eql(true) } 
    end 
end 

Услуга:

class GeocodeUserAuthorizer 
    def initialize(country_code:) 
    @country_code = country_code 
    end 

    def authorize! 
    check_country 
    end 

    protected 

    def check_country 
     user_continent = ISO3166::Country.new(@country_code).continent 

     if user_continent == 'Africa' 
     return false 
     else 
     return true 
     end 
    end 
end 
Смежные вопросы