假设我有以下代码.

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

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

但round\u类型方法和测试代码不支持视频类型.因此,当我在生产中遇到错误时,我最终会意识到这一点.

我想知道在错误发生之前,我必须更改什么方法.

所以,这是我的问题:当我必须在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方法时,最后一个规范将失败.

100

Ruby-on-rails相关问答推荐

为什么Rails数值验证器不使用规格化值?

在Ruby on Rails中获取堆栈级别太深错误(&Q)

在PDF生成中渲染 colored颜色

如何避免 activesupport 中的循环参数引用警告

heroku 推送错误:无法检测到 rake 任务

Rails Migration将字符串转换为整数?

Factory Girl + Mongoid 在fixture 中嵌入文档

在允许用户使用设计(rails)登录之前判断用户是否处于活动状态

在命名空间内设计

在 Rails 4 中检测用户代理 - 读取 HTTP 标头

是否有与 PHP 的 isset() 等效的 Rails?

如何在 Rails 应用程序中使用长 id?

使用 oauth 和 twitter ruby​​ gem 时不断收到 OAuth::Unauthorized 错误

加载常量时自动加载常量时检测到循环依赖

如何在 Rails 应用程序中测试 ElasticSearch (Rspec)

在 Rails 中,在特定时区创建特定时间(不是现在)的最佳方式是什么?

Ruby/Rails CSV 解析,UTF-8 中的无效字节序列

Rails.cache 在测试之间被清除了吗?

Rails:您已经激活了 rake 10.3.1,但您的 Gemfile 需要 rake 10.2.2 (Gem::LoadError)

我如何为 Rails3/Bundler 供应 gems