RSpec API控制器测试

问题描述 投票:0回答:1

起初,对不起我的英文:)

我需要在Ruby on Rails应用程序(v 4.2.0)中实现API控制器的测试。当我向GET Advertising Sources请求时,我有一个像这样的json响应:

{"advertising_sources":[{"id":59,"title":"accusantium"},{"id":60,"title":"assumenda"}]} 

JSON响应模板由前端开发人员定义。现在我尝试为以下内容创建测试:1。JSON大小(2个广告源)2。包含属性(id,title)

我的测试:

it 'returns list of advertising sources' do
  expect(response.body).to have_json_size(2)
end

%w(id title).each do |attr|
  it "returns json with #{attr} included" do
    hash_body = JSON.parse(response.body)
    expect(hash_body).to include(attr)
  end
end

失败:

1. Failure/Error: expect(response.body).to have_json_size(2)
   expected {"advertising_sources":[{"id":59,"title":"accusantium"},{"id":60,"title":"assumenda"}]} to respond to `has_json_size?`

2. Failure/Error: expect(hash_body).to include(attr)

   expected {"advertising_sources" => [{"id" => 71, "title" => "necessitatibus"}, {"id" => 72, "title" => "impedit"}]} to include "id"
   Diff:
   @@ -1,2 +1,2 @@
   -["id"]
   +"advertising_sources" => [{"id"=>71, "title"=>"necessitatibus"}, {"id"=>72, "title"=>"impedit"}],

任何人都可以帮我纠正我的测试代码吗?谢谢!

ruby-on-rails api ruby-on-rails-4 rspec rails-api
1个回答
1
投票

根据您的响应形状和您有兴趣测试的特性,您可以按如下方式编写测试:

describe 'advertising_sources' do
  let(:parsed_response_body) { JSON.parse(response.body) }
  let(:advertising_sources) { parsed_response_body['advertising_sources'] }

  it 'returns list of advertising sources' do
    expect(advertising_sources.size).to eq(2)
  end

  %w(id title).each do |attr|
    it "returns json with #{attr} included" do
      advertising_sources.each { |source| expect(source.keys).to include(attr) }
    end
  end
end

我个人会进一步简化这个:

describe 'advertising_sources' do
  let(:parsed_response_body) { JSON.parse(response.body) }
  let(:advertising_sources) { parsed_response_body['advertising_sources'] }

  it 'returns list of advertising sources' do
    expect(advertising_sources.size).to eq(2)
  end

  it 'includes an id and title for each source' do
    advertising_sources.each { |source| expect(source.keys).to match_array(%w(id title)) }
  end
end
© www.soinside.com 2019 - 2024. All rights reserved.