当我必须在 rspec 中更改方法时,如何检测时间?

How can I detect the timing when I have to change a method in rspec?

假设我有以下代码。

class Answer
  enum type: %i[text checkbox image]

  def round_type
    case answer.type
    when text, checkbox
      :text
    when image
      :multimedia
    else
      raise 'Unknown type'
    end
  end  
end
require 'rails_helper'

RSpec.describe Answer, type: :model do
  describe '#round_type' do
    context 'when type is text' do
      it 'returns text' do
        # omitted 
      end
    end
    context 'when type is checkbox' do
      it 'returns text' do
      end
    end
    context 'when type is image' do
      it 'returns multimedia' do
      end
    end    
  end
end

然后我将视频类型添加到枚举中。当类型是视频时,我希望方法 returns 多媒体。

但是round_type方法和测试代码不支持视频类型。所以当我在生产中出错时,我终于意识到了。

我想知道在错误发生之前我必须更改方法。

所以,这是我的问题:如何检测必须在 rspec 中更改方法的时间?

如果我对你的理解是正确的,你必须让你的规格更动态一点,你还必须测试 else 语句:

class Answer
  enum type: %i[text checkbox image]

  def round_type
    case type
    when 'text', 'checkbox'
      :text
    when 'image'
      :multimedia
    else
      raise 'Unknown type'
    end
  end  
end
RSpec.describe Answer, type: :model do
  describe '#round_type' do
    it 'raises error for unknown type' do
      # empty `type` is an unknown type in this situation
      expect { Answer.new.round_type }.to raise_error
    end

    it 'does not raise error for available types' do
      # NOTE: loop through all types and check that `round_type` method
      #       recognizes each one.
      Answer.types.each_key do |key|
        expect { Answer.new(type: key).round_type }.to_not raise_error
      end
    end
  end
end

下次添加新的 type 而忘记更新 round_type 方法时,最后的规范将失败。

https://relishapp.com/rspec/rspec-expectations/v/3-11/docs/built-in-matchers/raise-error-matcher