【问题标题】:RSpec: How to properly test class method that loops through a collection / calls instance methodRSpec:如何正确测试循环通过集合/调用实例方法的类方法
【发布时间】:2018-07-10 16:01:40
【问题描述】:

考虑以下类和类方法:

class Foo < ActiveRecord::Base
    scope :active, -> { where(deleted: false) }

    class << self
      def some_class_method
        active.each do |foo|
          foo.some_instance_method
        end
      end
    end
end

在 RSpec 中测试这种方法的最佳实践是什么?到目前为止,我所学到的表明我应该确保 Foo 的每个活动实例接收对some_instance_method 的调用,但如果我要对Foo.some_class_method 做出期望,据我所知,我不能断言对任何 Foo 实例的嵌套期望。

任何帮助将不胜感激!

【问题讨论】:

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


    【解决方案1】:

    我会采取的方法是单独测试some_instance_method,比如:

    it 'should return some value' do
      expect(foo.some_instance_method).to eq('some value')
    end
    

    然后您可以运行类方法并测试转换是否按预期发生:

    context 'Foo#some_class_method' do
      it 'should have some effect' do
        expect(some_comparison_variable).to eq('some_before_state')
        Foo.some_class_method
        expect(some_comparison_variable).to eq('some_after_state')
      end
    end
    

    【讨论】:

    • 我想到了,但这不是有效地双重测试some_instance_method吗?
    • 同一个方法测试两次没有坏处。
    • 你可以做expect(some_instance_of_Foo).to receive(:some_instance_method)第二次。
    猜你喜欢
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    • 2021-12-12
    • 2014-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多