Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby RSpec一个衬垫到测试对象';s属性_Ruby_Rspec - Fatal编程技术网

Ruby RSpec一个衬垫到测试对象';s属性

Ruby RSpec一个衬垫到测试对象';s属性,ruby,rspec,Ruby,Rspec,让我们假设以下情况 class A attr_accessor :name def initialize(name) @name = name end end subject { A.new('John') } 那么我想要一些像这样的单尾班轮 it { should have(:name) eq('John') } 有可能吗?是的,有可能,但是您想要使用的语法(在任何地方都使用空格)具有have(:name)和eq('John')都是应用于方法sho

让我们假设以下情况

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

subject { A.new('John') }
那么我想要一些像这样的单尾班轮

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

有可能吗?

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

require 'rspec/expectations'

RSpec::Matchers.define :have do |meth, expected|
  match do |actual|
    actual.send(meth) == expected
  end
end
这将为您提供以下语法:

it { should have(:name, 'John') }
此外,您还可以使用


方法从RSpec中去除its。相反,您应该能够这样做一行:

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

参考资料:

谢谢。但我发现使用它的方法使它更自然。“你能把它添加到你的答案中吗?”米沙斯利乌萨雷夫补充道。
it { is_expected.to have_attributes(name: 'John') }
person = Person.new('Jim', 32)

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