2013-12-20 41 views
0

我有一個方法是複製一個變量並將其分發到不同的對象。我想驗證正在發送的對象確實是不同的對象,而不是指向同一對象的不同指針。Rspec嘲弄,驗證收到的對象是不一樣的

我的測試目前看起來是這樣的:

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方法?

回答

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 
+0

我需要使用'... expect(arg).t o_not不等於(arg1)'而不是'eq'。顯然'eq'相當於檢查值的'==',而不是實際的對象。 – Automatico

+0

確實。對不起,感謝您指出。我已經更新了答案。 –

+0

這非常有趣。如果你想檢查用特定對象調用方法,你也需要使用這個方法,但是改爲'.to equal(data)'。正常的'receive(:method).with(data)'不會測試數據是同一個對象。 – Automatico

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