如何在Ruby中使用Faker处理重复密钥

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

如果Faker为名称字段生成现有名称,该如何循环?

名称字段是此表中的主键。当找到重复的名称时,它将一直生成,直到找到另一个名称。

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

> client = Crud.new 
> response = client.create
> id = JSON.parse(response)['id']
> client.retrieve(id)
ruby httparty
2个回答
1
投票

根据您的Faker版本,您可以使用unique来确保唯一的值:

unique

1
投票

nome = Faker::Name.unique.first_name 应始终在每次测试运行时返回唯一的名称。需要注意的是,如果生成大量数字,则可能会用尽唯一值并引发错误。

您还必须在测试运行之间清除数据库,否则可能会产生冲突。

Faker::Name.unique.first_name

© www.soinside.com 2019 - 2024. All rights reserved.