2016-12-05 85 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 

而且你会想,如果你想authorize!使用它没有@符号类增加一个attr_readeruser_country_code

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