【问题标题】:How can I detect the timing when I have to change a method in rspec?当我必须更改 rspec 中的方法时,如何检测时间?
【发布时间】:2022-06-26 14:56:03
【问题描述】:

假设我有以下代码。

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

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

但是 round_type 方法和测试代码不支持视频类型。所以当我在生产中遇到错误时,我最终会意识到这一点。

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

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

【问题讨论】:

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


    【解决方案1】:

    如果我理解正确,你必须让你的规范更加动态,你还必须测试else 语句:

    class Answer < ApplicationRecord
      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

    【讨论】:

    • 这正是我想知道的。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多