在rspec中检查复杂结果

在rspec中检查复杂结果,rspec,matcher,Rspec,Matcher,我有一个方法get_something,它返回一个复杂的对象。我想检查这个复杂对象的特定公共属性是否为字符串 这就是我知道我可以测试的原因: require 'rspec/autorun' class MySubject ComplexObject = Struct.new(:type, :trustworthiness) def get_something ComplexObject.new('serious', 100) end end RSpec.describe

我有一个方法get_something,它返回一个复杂的对象。我想检查这个复杂对象的特定公共属性是否为字符串

这就是我知道我可以测试的原因:

require 'rspec/autorun'

class MySubject
  ComplexObject = Struct.new(:type, :trustworthiness)

  def get_something
    ComplexObject.new('serious', 100)
  end
end

RSpec.describe MySubject do
  describe '#get_something' do
    it 'returns an serious object' do
      expect(subject.get_something.type).to eq('serious')
    end

    it 'returns an trustworthy object' do
      expect(subject.get_something.trustworthiness).to be > 90
    end
  end
end
我想知道是否有一种方法可以这样写下期望:

expect(subject.get_something).to have_attribute(:type).to eq('serious')
expect(subject.get_something).to have_attribute(:trustworthiness).to be > 90
这背后的原因是我想说明我对get_something的结果感兴趣,而不是对ComplexObject实例感兴趣

这个场景已经有匹配器了吗?如果没有,您将如何编写此规范,尤其是当您对正确设置多个属性感兴趣时

提前感谢

Matchers没有您想要使用的to方法。它们只接受一个预期参数,并进行真实性评估,因此您需要传递一个散列,如下所示:

expect(subject.get_something).to have_attribute(method: :type, value: 'serious')
expect(subject.get_something).to have_attribute(method: :trustworthiness, value: ->(v) { v > 90 } )
在解释值参数时具有明显的复杂性

另一种方法是使用its功能,它在RSpec 3中移动到一个单独的gem,如:

RSpec.describe MySubject do
  describe '#get_something' do
    subject(:get_something) { MySubject.new.get_something }
    its(:type) { should eq 'serious'}
    its(:trustworthiness) { should be > 90 }
  end
end