2

我正在编写请求规范,并且无法以 json 格式测试 api 响应。我正在使用capybarafabricator,这是我尝试的代码...

    context 'discounts in api' do
      let(:user) { Fabricate(:user, activated: true) }
      let(:api_token) { user.api_token }

      before { visit api_url_for('/v1/discount_coupons', api_token) }

      it 'returns coupons collection' do
        Fabricate(:discount_coupon, code: 'Discount One', global: true)

        save_screenshot("tmp/capybara/screenshot-#{Time::now.strftime('%Y%m%d%H%M%S%N')}.png")
        save_and_open_page


        expect(json_response['total_records']).to eq 1
        expect(json_response['total_pages']).to eq 1
        expect(json_response['page']).to eq 0
        expect(json_response['discount_coupons'].size).to eq 1
        expect(json_response['discount_coupons'][0]['code']).to eq 'Discount One'
      end
end

我得到的回应是这样的

{"discount_coupons":[{"id":11,"code":"Discount One","type":"DiscountPercentage","amount_off":1.5,"global":true,"expires_on":null,"vendors":[]}],"page":0,"total_pages":1,"total_records":1}

并且错误阻止我运行成功的测试,

Failure/Error: expect(json_response['total_pages']).to eq 1
             NoMethodError:
               undefined method `body' for nil:NilClass 

我认为我对 json_response 的期望是错误的或缺少某些东西,请有人帮我以帅气的方式做到这一点,提示我如何使用键和值进行测试。

4

2 回答 2

2

测试 API 的最佳方法是使用 rspec,因为您只需要这样做:

it "should return the expected information" do
  get "/url"

  parsed_response = JSON.parse(response.body)
  expect(parsed_response["key"]).to eq(whatever)
end

it "should update the expected entity" do
  post "/url", body, headers

  parsed_response = JSON.parse(response.body)
  expect(parsed_response["key"]).to eq(whatever)
end

你的测试失败了,因为你试图解析一个空的响应。Fabric 可能会失败,或者调用可能是错误的。

于 2014-06-25T11:52:55.233 回答
0

我认为问题可能是您正在访问之前块中的页面,然后稍后在断言块中生成折扣券。尝试像这样移动代码,看看它是否会产生更好的结果。

context 'discounts in api' do
  let(:user) { Fabricate(:user, activated: true) }
  let(:api_token) { user.api_token }

  before do
    Fabricate(:discount_coupon, code: 'Discount One', global: true)
    visit api_url_for('/v1/discount_coupons', api_token)
  end

  it 'returns coupons collection' do
    save_screenshot("tmp/capybara/screenshot-#{Time::now.strftime('%Y%m%d%H%M%S%N')}.png")
    save_and_open_page

    expect(json_response['total_records']).to eq 1
    expect(json_response['total_pages']).to eq 1
    expect(json_response['page']).to eq 0
    expect(json_response['discount_coupons'].size).to eq 1
    expect(json_response['discount_coupons'][0]['code']).to eq 'Discount One'
  end
于 2014-06-26T11:50:21.407 回答