RSpec API 控制器测试

RSpec API controllers testing

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

我需要在 Rails 应用程序 (v 4.2.0) 的 Ruby 中实现 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"}],

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

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

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