ruby - 我可以使用 rspec 模拟来 stub 版本常量吗?

标签 ruby rspec constants mocking

我的代码只需要在特定版本的 ActiveRecord 上运行(解决旧 AR 库上的错误的方法)。此代码测试 ActiveRecord::VERSION 常量的值以查看它是否需要运行。

有没有办法在 rspec 中模拟这些常量,这样我就可以测试该代码路径,而无需在测试机器上安装正确的 ActiveRecord gem?

最佳答案

我最终编写了一个辅助方法来让我在执行代码块时覆盖常量:

def with_constants(constants, &block)
  constants.each do |constant, val|
    Object.const_set(constant, val)
  end

  block.call

  constants.each do |constant, val|
    Object.send(:remove_const, constant)
  end
end

将此代码放入您的 spec_helper.rb 文件后,可以按如下方式使用:

with_constants :RAILS_ROOT => "bar", :RAILS_ENV => "test" do
  code goes here ...
end

希望这对你有用。

关于ruby - 我可以使用 rspec 模拟来 stub 版本常量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1698335/

相关文章:

winapi - SetNamedSecurityInfo 采用可写路径;缓冲区应该有多大?

c++ - 如何通过 remove_cv 函数推断类型(const volatile int* vs const volatile int vs int * const volatile)

ruby - 如何最小化嵌套的 if 语句? ( ruby )

ruby-on-rails - Elasticsearch-rails正在搜索错误的索引

ruby-on-rails - VCR 正在返回 UnhandledHTTPRequestError

ruby - 使用 RSpec,常量是否描述了一个大禁忌?

c - 修改了c中的一个常量

ruby-on-rails - Rails 的 ActiveRecord 序列化 :attr method gives "Missing Class or module error"

ruby - 如何指定 chromedriver 二进制文件的位置

ruby-on-rails - 来自 csv.read 模拟文件的 rspec 测试结果