RSpec单行测试对象的属性

时间:2013-11-08 09:24:57

标签: ruby rspec

让我们假设以下情况

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

subject { A.new('John') }

然后我想要像这样的单行

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

有可能吗?

3 个答案:

答案 0 :(得分:5)

方法 已从RSpec https://gist.github.com/myronmarston/4503509中删除。相反,你应该能够这样做一个班轮:

it { is_expected.to have_attributes(name: 'John') }

答案 1 :(得分:2)

是的,这是可能的,但您想要使用的语法(在任何地方都使用空格)具有have(:name)eq('John')是应用于方法should的所有参数的含义。所以你必须预先定义那些不能成为你的目标的东西。也就是说,您可以使用rspec custom matchers来实现类似的目标:

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') }

答案 2 :(得分:0)

person = Person.new('Jim', 32)

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

参考:rspec have-attributes-matcher

相关问题