使用Rspec共享示例测试Ruby类';属性

使用Rspec共享示例测试Ruby类';属性,ruby,rspec,rspec3,Ruby,Rspec,Rspec3,尝试使用Rspec共享示例测试两个类似URL的属性: 规范/实体\u规范rb spec/shared_examples/a_url.rb 显然,我需要向共享示例发送对:url和:wikipedia\u url属性的引用,但是如何?您可以“使用块为共享组提供上下文”,如前所述 需要“设置” RSpec.shared_示例“集合对象”是否 描述“您的共享示例块接受一个参数方法,但您没有将一个参数传递给它。但是,您非常接近。只需更改: context ':url attribute' do it_

尝试使用Rspec共享示例测试两个类似URL的属性:

规范/实体\u规范rb spec/shared_examples/a_url.rb 显然,我需要向共享示例发送对
:url
:wikipedia\u url
属性的引用,但是如何?

您可以“使用块为共享组提供上下文”,如前所述

需要“设置”
RSpec.shared_示例“集合对象”是否

描述“您的共享示例块接受一个参数
方法
,但您没有将一个参数传递给它。但是,您非常接近。只需更改:

context ':url attribute' do
  it_behaves_like "a URL", :url
end
现在,我们将
:url
符号作为
方法
传递给共享示例。然后,您需要将对
:方法=
的引用更改为
主题(这将失败,因为它实际上是
主题。方法=
)发送到
主题。发送(“{method}=”,value)
因此我们实际上是在调用方法
url=

it "ensures that :#{method} does not exceed 255 characters" do
  subject.send("#{method}=", 'http://' + '@' * 256)
  expect(subject).to_not be_valid
end
综上所述,我建议将局部变量的名称从
method
更改为其他名称(甚至可能是
method\u name
),以避免将
method()
方法和局部变量
method
混淆

require "set"

RSpec.shared_examples "a collection object" do
  describe "<<" do
    it "adds objects to the end of the collection" do
      collection << 1
      collection << 2
      expect(collection.to_a).to match_array([1, 2])
    end
  end
end

RSpec.describe Array do
  it_behaves_like "a collection object" do
    let(:collection) { Array.new }
  end
end

RSpec.describe Set do
  it_behaves_like "a collection object" do
    let(:collection) { Set.new }
  end
end
context ':url attribute' do
  it_behaves_like "a URL", :url
end
it "ensures that :#{method} does not exceed 255 characters" do
  subject.send("#{method}=", 'http://' + '@' * 256)
  expect(subject).to_not be_valid
end