2017-03-07 22 views
0

仍在學習Rspec作爲一個整體,所以感謝耐心。RSpec期望散列包含一組鍵值對

返回值是這樣的:

{ supermodel: { 
    'id': 1, 
    'name': 'J', 
    'model_attributes': [ 
     {attr1: 'T', attrA: 1}, 
     {attr2: 'F', attrB: 2}, 
     {attr3: 'T', attrC: 3} 
     ], 
    } 
} 

試圖讓說,名爲「model_attributes」散列關鍵字包含包括以下鍵值對數組的值的期待 - {attr2:F, attrB: 2}{attr3: T, attrC: 3}

任何有識之士都會受到歡迎。

+0

你的方法的結果是這樣的.'是無效的Ruby對象,請仔細檢查它;) –

+0

也許這有幫助嗎? http://apidock.com/rspec/Spec/Mocks/ArgumentMatchers/hash_including – trueunlessfalse

+0

真@AndreyDeineko將斷言重新格式化爲更多的紅寶石。謝謝! – JoaWa

回答

0
describe 'Stuff' do 
    let(:model_attributes) do 
    [ 
     {attr1: 'T', attrA: 1}, 
     {attr2: 'F', attrB: 2}, 
     {attr3: 'T', attrC: 3} 
    ] 
    end 
    let(:result) do 
    { supermodel: 
     { 
     'id': 1, 
     'name': 'J', 
     'model_attributes': model_attributes 
     } 
    } 
    end 

    it 'has the correct model_attributes value' do 
    expect(result.dig(:supermodel, :model_attributes)).to eq(model_attributes) 
    end 
end 
+0

謝謝Andrey--最終借用了這個策略。 – JoaWa

0

嘗試

describe 'ModelAttributes' do 
    let(:model_attributes) { [{ attr1: 'T', attrA: 1 }, 
          { attr2: 'F', attrB: 2 }, 
          { attr3: 'T', attrC: 3 }] } 

    it 'includes the required attributes' do 
    expect(model_attributes).to include({ attr2:'F', attrB: 2 }, { attr3: 'T', attrC: 3 }) 
    end 
end 
0

現在回想起來,這是一個容易得多了。簡單地遍歷散列並期望值是最簡單的方法。重構結束了我這樣做:

supermodel[:model_attributes].each do |attr| 
    expect(attr[:attrB])to be 2 
end 

感謝所有的建議,帶領我走下了正確的道路。

相關問題