首页 > 解决方案 > 无法从规范中的 API 检索记录

问题描述

当我运行时retrieve显示以下错误:

参数数量错误(给定 0,预期为 1)(ArgumentError)

这里的一个人试图帮助我,但我认为我的问题很不方便,因为我真的无法解决它。我只需要这个来解决这个问题。

class Crud
  include HTTParty
  base_uri 'http://dummy.restapiexample.com/api/v1'

  def create 
    nome    = Faker::Name.first_name
    salario = Faker::Number.decimal(l_digits: 4, r_digits: 2)
    idade   = Faker::Number.number(digits: 2)
    #note, you should pass body as JSON string
    body = { name: nome, salary: salario, age: idade }.to_json

    headers = {
      'Accept' => 'application/vnd.tasksmanager.v2',
      'Content-Type' => 'application/json'
    }

    self.class.post('/create', body: body, headers: headers) 
  end

  def retrieve(id)
    self.class.get("/employee/#{ id }")
  end 
end

我正在尝试在规格中使用它

Consult employee Quando("é enviada a requisição para consultar o empregado") do 
  _manter_user.create 
  expect(_manter_user.create.code).to eq (200) 
  puts _manter_user.create.body 
end

Então("posso visualizar as informações retornadas") do 
  expect(@manter_user.retrieve.code).to eq (200) 
  puts _manter_user.create.body 
end 

标签: ruby-on-railsruby

解决方案


问题在于多次调用create,您需要将结果存储在变量中。您还需要在创建后立即检索实例 - 规范的顺序可能会发生变化,并且您可能会遇到在创建之前尝试检索的情况

Some spanish? text goes here do 
  created = manter_user.create 
  expect(created.code).to eq (200) 
  puts created.body 

  id = JSON.parse(created)['id']
  retrieved = manter_user.retrieve(id)

  expect(retrieved.code).to eq (200)
  puts retrieved.body
end    

推荐阅读