让我们假设以下情况

class A
    attr_accessor :name
    def initialize(name)
        @name = name
    end
end

subject { A.new('John') }

那我想拥有一些这样的单线

it { should have(:name) eq('John') }

有可能吗?

有帮助吗?

解决方案 2

是的,这是可能的,但是您要使用的语法(到处都有空格)的暗示是 have(:name)eq('John') 所有参数都适用于该方法 should. 。因此,您必须预先定义这些,这不是您的目标。也就是说,你可以使用 RSPEC自定义匹配器 实现类似目标:

require 'rspec/expectations'

RSpec::Matchers.define :have do |meth, expected|
  match do |actual|
    actual.send(meth) == expected
  end
end

这为您提供了以下语法:

it { should have(:name, 'John') }

另外,您可以使用 its

its(:name){ should eq('John') }

其他提示

方法 它的 从RSPEC中删除 https://gist.github.com/myronmarston/4503509. 。相反,您应该能够这样做一个衬里:

it { is_expected.to have_attributes(name: 'John') }
person = Person.new('Jim', 32)

expect(person).to have_attributes(name: 'Jim', age: 32)

参考: RSPEC具有捕获量

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top