have_attributes
匹配器
使用 have_attributes
匹配器指定对象的属性是否与预期属性匹配
Person = Struct.new(:name, :age)
person = Person.new("Jim", 32)
expect(person).to have_attributes(:name => "Jim", :age => 32)
expect(person).to have_attributes(:name => a_string_starting_with("J"), :age => (a_value > 30) )
如果实际值不响应任何预期属性,则匹配器将失败
expect(person).to have_attributes(:name => "Jim", :color => 'red')
基本用法
给定一个名为“basic_have_attributes_matcher_spec.rb”的文件,其中包含
Person = Struct.new(:name, :age)
RSpec.describe Person.new("Jim", 32) do
it { is_expected.to have_attributes(:name => "Jim") }
it { is_expected.to have_attributes(:name => a_string_starting_with("J") ) }
it { is_expected.to have_attributes(:age => 32) }
it { is_expected.to have_attributes(:age => (a_value > 30) ) }
it { is_expected.to have_attributes(:name => "Jim", :age => 32) }
it { is_expected.to have_attributes(:name => a_string_starting_with("J"), :age => (a_value > 30) ) }
it { is_expected.not_to have_attributes(:name => "Bob") }
it { is_expected.not_to have_attributes(:age => 10) }
it { is_expected.not_to have_attributes(:age => (a_value < 30) ) }
# deliberate failures
it { is_expected.to have_attributes(:name => "Bob") }
it { is_expected.to have_attributes(:age => 10) }
# fails if any of the attributes don't match
it { is_expected.to have_attributes(:name => "Bob", :age => 32) }
it { is_expected.to have_attributes(:name => "Jim", :age => 10) }
it { is_expected.to have_attributes(:name => "Bob", :age => 10) }
end
当我运行 rspec basic_have_attributes_matcher_spec.rb
那么输出应包含“14 个示例,5 个失败”。