首页 文章

将变量传递给rspec测试

提问于
浏览
-1

我是一个相当新的rspec测试,我有一个问题,试图测试用户的位置 . 这是一个模拟country_code阻止特定区域垃圾邮件行为的测试 .

这是我的服务代码:

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

这是我的spec文件的代码:

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

这是失败代码:

失败:1)GeocodeUserAuthorizer,用户从授权国家/地区连接失败/错误:它{expect(GeocodeUserAuthorizer.new.authorize!(user_country_code:{“CA”})) . 到eql(true)} ArgumentError:缺少关键字: user_country_code# . / app / services / geocode_user_authorizer.rb:2:初始化'#./spec/services/geocode_user_authorizer_spec.rb:16:innew'#./spec/services/geocode_user_authorizer_spec.rb:16:in块(3个级别) )在'#(./spec/spec_helper.rb:56:in`block(2个级别)'中的<top(必要)>'# . / spec / slap / helper.rb:56:inblock(3个级别)中

有人可以帮忙吗?

2 回答

  • 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! 在没有 @ 符号的情况下使用 authorize! ,您还需要在类中为 user_country_code 添加 attr_reader .

  • 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
    

相关问题