【问题标题】:Adding RSpec coverage for a method with if/else logic为具有 if/else 逻辑的方法添加 RSpec 覆盖率
【发布时间】:2019-07-02 01:21:14
【问题描述】:

所以我对 RSpec 和 Rails 还很陌生,我一直在尝试尽可能多地学习 RSpec,但我真的很难为其中包含逻辑的方法实现覆盖。

我正在练习的应用程序使用覆盖率百分比来确保我正确覆盖了我正在实现的代码并且我缺少以下方法的覆盖率:

def initialize_business
  businesses.each do |business|
    if business.type == 'Restaurant'
      @business_type = Business::Restaurant.new(json_directory: 'restaurant.json')
    elsif business.type = 'Bar'
      @business_type = Business::Bar.new(json_directory: 'bar.json')
    else
      @business_type = Business::Other.new(json_directory: 'other_business.json')
    end
  end
  business_type = @business_type
  initialize_business_creator(business_type)
end

我最初尝试提供覆盖范围(忽略了其他不相关的规范),但我什至难以实施任何覆盖范围,因为我对 RSpec 太陌生了:

describe '#initialize_business' do
    subject do
      described_class.new([business], business_sample_file).
      initialize_business_creator
    end

    it 'assigns a value to @business_type' do
      expect(assigns(@business_type)).to_not be_nil
    end
  end
end

我只是在寻找有关如何为此类方法实施规范的帮助和/或指导,我感谢任何和所有帮助。谢谢!

【问题讨论】:

    标签: ruby-on-rails rspec rspec-rails


    【解决方案1】:

    您需要创建场景来测试代码的分支 (if, elsif, else)

    你可以做的是,你可以mock返回type的方法来得到你想要的结果。

    例如,如果您想测试您的 if 条件是否已评估并且该分支中的代码是否成功运行。

    你可以这样做:

    describe '#initialize_business' do
        subject do
          described_class.new([business], business_sample_file).
          initialize_business_creator
        end
    
        it 'assigns a value to @business_type' do
          expect(assigns(@business_type)).to_not be_nil
        end
    
        context "when business type is 'Restaurant'" do
            before { allow_any_instance_of(Business).to receive(:type).and_return "Restaurant"
        end
    
        it "should create data from restaurant.json" do
            //here you can write expectations for your code inside if statement
    
        end
      end
    end
    

    行:

    allow_any_instance_of(Business).to receive(:type).and_return "Restaurant"

    无论何时调用business.type,都会返回一个“Restaurant”字符串。

    同样,您可以使此方法返回其他值,例如“Bar”并检查您的 elsif 场景。

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2020-11-09
      • 2016-03-24
      • 1970-01-01
      • 2017-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-19
      相关资源
      最近更新 更多