2016-06-20 1 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 
関連する問題