我有一个复制变量并将其分发给不同对象的方法。我想验证正在发送的对象确实是不同的对象,而不是指向同一对象的不同指针。
我的测试目前看起来像这样:
it 'uses different objects when false' do
object1 = SomeClass.new
object2 = SomeClass.new
data = "something"
MasterClass.register(object1)
MasterClass.register(object2)
#Not correct:
expect(object1).to_not receive(:get_data).with(data)
expect(object2).to_not receive(:get_data).with(data)
#False is supposed to mean
# "create new objects for each call to get_data for the SomeClass"
MasterClass.distribute_data(data, false)
end
我知道我可以使用a.equal?(b)
测试对象属性的相等性,但是当我想测试的对象是rspec mock中with
方法中的参数时,我怎么能这样做? / p>
答案 0 :(得分:1)
这应该有效,向receive
匹配器添加一个块,并使用匹配器be
:
describe "Example" do
it "should find something, but not using the original variable" do
text = "Hi!"
original = "!"
copied = original.clone
expect( text ).to receive(:include?) { |x| x.should_not be original; true }
text.include?( copied ).should be_true
end
end
您的等效内容可能如下所示:
expect(object1).to receive(:get_data) do |d|
d.should_not be data
d.should == data
end
答案 1 :(得分:1)
这是一个坚持使用“expect”语法的版本:
it 'uses different objects when false' do
object1 = SomeClass.new
object2 = SomeClass.new
data = "something"
MasterClass.register(object1)
MasterClass.register(object2)
arg1 = nil
expect(object1).to receive(:get_data) {|arg| arg1 = arg}
expect(object2).to receive(:get_data) {|arg| expect(arg).to_not equal(arg1)}
#False is supposed to mean
# "create new objects for each call to get_data for the SomeClass"
MasterClass.distribute_data(data, false)
end