RSpec API控制器测试

时间:2019-03-15 16:21:47

标签: ruby-on-rails api ruby-on-rails-4 rspec rails-api

首先,对不起我的英语了:)

我需要在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,标题)

我的测试:

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"}],

有人可以帮助我更正测试代码吗? 谢谢!

1 个答案:

答案 0 :(得分: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