2016-06-20 33 views
0

我有一個端點,它使用從ActiveModelSerializer添加的對象的屬性+屬性進行響應。我想編寫一個測試來檢查響應是否有密鑰。如何測試API響應在RSpec中具有密鑰

讓我們假設說對象(比如一棵樹)具有這些鍵

expected_tree_attributes = [:height, :age, :color]

如何正確寫這個測試?我可以寫:

subject { post :obtain_tree_info, { id: tree.id } } 

response = JSON.parse(subject.body) 
expected(response).to include(*expected_tree_attributes) 

那是......可以接受嗎?

回答

0

請考慮使用rspec-api-matchers gem

airborne gem

有了這些,你可以這樣做:

# api_matchers 
response = JSON.parse(subject.body) 
expect(response).to be_success 
expect(response).to have_json_node(:height).with(tree.height) 
expect(response).to have_json_node(:age).with(tree.age) 
expect(response).to have_json_node(:color).with(tree.color) 

# or 

expect(response).to have_json_node(:age).with("123") 

空降

describe 'sample spec' do 
    it 'should validate types' do 
    post '/api/v1/obtain_tree_info', {id: tree.id} 
    expect_json_types(height: :int, age: :int_or_null, color: :string) 
    end 
end