使用Cucumber编写测试时如何验证api的响应

时间:2018-09-01 14:04:29

标签: ruby-on-rails cucumber

我正在一个Rails项目中,我必须使用Cucumber测试API。我必须测试POST类型的API,并且需要验证其响应。我已经尝试过类似的东西:

When(/^I make abc API call$/) do
  @url = 'http://example.com/api/abc'
  @params = '{
                data: {
                  type: "abc",
                  attributes: {
                    title: "example",
                    all_day: "0",
                    start_date: "1409175049",
                    end_date: "1409175049"
                  }
                }
              }'
  @login_token = 'pHufpGplLTYJnmWh5cqKoA'
end

Then(/^It should return success for abc$/) do
  post 'http://example.com/api/abc', body: @params,
                                 headers: { 'Accept' => 'application/json',
                                            'login_token' => @login_token,
                                            'Content-Type' => 'application/json' }
end

但是我不确定如何从响应中验证状态代码以及响应中的所有属性。像这样:

Then(/^It should return success for abc$/) do
  post 'http://example.com/api/abc', body: @params,
                                 headers: { 'Accept' => 'application/json',
                                            'login_token' => @login_token,
                                            'Content-Type' => 'application/json' }
  .to_return(status: 200, body: '{ title: "abc" }')
end

我该如何实现?

1 个答案:

答案 0 :(得分:3)

如果您使用的是Capybara,这应该对您有用:

Then /^I should get a response with status (\d+)$/ do |status|
  response = post 'http://example.com/api/abc', body: @params,
                                                headers: { 'Accept' => 'application/json',
                                                           'login_token' => @login_token,
                                                           'Content-Type' => 'application/json' }
  response.status_code.should include(status.to_i)
end