【问题标题】:Calling rspec methods from different file从不同的文件调用 rspec 方法
【发布时间】:2021-06-09 21:42:45
【问题描述】:

我正在尝试在我的代码中编写一个类来包装一些 RSpec 调用。但是,每当我尝试访问 rspec 事物时,我的班级根本看不到方法。

我在spec/support/helper.rb中定义了以下文件

require 'rspec/mocks/standalone'

module A
  class Helper
    def wrap_expect(dbl, func, args, ret)
      expect(dbl).to receive(func).with(args).and_return(ret)
    end
  end
end

我得到了NoMethodError: undefined method 'expect',尽管需要正确的模块。请注意,如果我在模块之前调用 rspec 函数,一切都会正确找到。

我已尝试将以下赞添加到我的spec_helper.rb

  config.requires << 'rspec/mocks/standalone'

但无济于事。

我设法在我的类中使用类变量并从全局上下文中传递函数,但这种解决方案似乎相当极端。我也能够传递测试上下文本身并存储它,但我也不想这样做。

【问题讨论】:

  • 将此行Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } 添加到spec_helper.rb
  • 我确实有那行,模块在我的测试中被正确导入,只是在 Helper 类中找不到 rspec 函数。

标签: ruby-on-rails ruby rspec


【解决方案1】:

expect 函数默认情况下仅与 it before 等 rspec-core 方法相关联。如果您需要在方法中包含期望,您可以尝试在帮助文件中添加 Rspec 匹配器类。

include RSpec::Matchers

【讨论】:

    【解决方案2】:

    该错误是因为调用expectself 不是当前的rspec 上下文RSpec::ExampleGroups,您可以通过记录self 进行检查

    module A
      class Helper
        def wrap_expect(dbl, func, args, ret)
          puts self
          expect(dbl).to receive(func).with(args).and_return(ret)
        end
      end
    end
    
    # test case
    A::Helper.new.wrap_expect(...) # log self: A::Helper
    

    很明显,A::Helper 不支持expect

    现在您有 2 个选项来构建帮助程序:(1) 模块或 (2) 使用当前测试用例上下文初始化的类:

    (1)

    module WrapHelper
     def wrap_expect(...)
       puts self # RSpec::ExampleGroups::...
       expect(...).to receive(...)...
     end
    end
    
    # test case
    RSpec.describe StackOverFlow, type: :model do
      include WrapHelper
      it "...." do
        wrap_expect(...) # call directly 
      end
    end
    

    (2)

    class WrapHelper
     def initialize(spec)
       @spec = spec 
     end
     
     def wrap_expect(...)
       puts @spec # RSpec::ExampleGroups::...
       @spec.expect(...).to @spec.receive(...)...
     end
    end
    
    # test case
    RSpec.describe StackOverFlow, type: :model do
      let!(:helper) {WrapHelper.new(self)}
      
      it "...." do
        helper.wrap_expect(...)
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-09
      • 1970-01-01
      • 2022-11-23
      • 2014-08-04
      • 2021-12-06
      • 1970-01-01
      • 2017-12-06
      • 1970-01-01
      相关资源
      最近更新 更多