【问题标题】:Rspec test yielding a method object from object constructorRspec测试从对象构造函数产生一个方法对象
【发布时间】:2014-10-08 07:48:21
【问题描述】:

我有以下代码:

def initialize
  yield method(:fulfill), method(:reject) if block_given?
end

我无法测试实际值 method(:fulfill)method(:reject) 是否已生成,因为在生成值时我还没有访问该对象的权限。

因此我想这样测试它:

expect do |b|
  PurePromise.new(&b)
end.to yield_with_args(PurePromise.instance_method(:fulfill), PurePromise.instance_method(:reject))

但是,UnboundMethod 不等于 Method,即使它引用相同的方法。

在匹配yield_with_args 的参数之前,有没有办法通过调用unbind 来转换产生值?

【问题讨论】:

    标签: ruby rspec yield


    【解决方案1】:

    我想到了一种方法,但是涉及到调用私有方法,所以感觉有点hacky

    subject = PurePromise.allocate
    expect do |b|
      subject.send(:initialize, &b)
    end.to yield_with_args(subject.method(:fulfill), subject.method(:reject))
    

    任何更好的解决方案将不胜感激。

    【讨论】:

      【解决方案2】:

      我找到了一种使用 rspec 3 的 composable matchers 的方法。

      RSpec::Matchers.define :be_a_bound_method_of do |unbound_method|
        match do |bound_method|
          bound_method.unbind == unbound_method
        end
      end
      
      RSpec::Matchers.alias_matcher :a_bound_method_of, :be_a_bound_method_of
      
      expect do |b|
        PurePromise.new(&b)
      end.to yield_with_args(
                 a_bound_method_of(PurePromise.instance_method(:fulfill)),
                 a_bound_method_of(PurePromise.instance_method(:reject))
             )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-15
        • 1970-01-01
        • 2014-09-13
        • 2013-10-20
        相关资源
        最近更新 更多