如何在 Ruby 中处理来自 Faker 的重复密钥
How to deal with a duplicate key from Faker in Ruby
如果 Faker 为 name 字段生成一个现有名称,我该如何循环?
名称字段是此table中的主键。当它找到一个重复的名字时,它将生成直到找到一个不同的名字。
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)
根据你的Faker版本,你可以使用unique
来确保唯一值:
nome = Faker::Name.unique.first_name
Faker::Name.unique.first_name
应始终 return 每个测试的唯一名称 运行。需要注意的是,如果您生成大量数字,它可能 运行 超出唯一值并引发错误。
您还必须在测试 运行 之间清除数据库,否则可能会产生冲突。
如果 Faker 为 name 字段生成一个现有名称,我该如何循环?
名称字段是此table中的主键。当它找到一个重复的名字时,它将生成直到找到一个不同的名字。
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)
根据你的Faker版本,你可以使用unique
来确保唯一值:
nome = Faker::Name.unique.first_name
Faker::Name.unique.first_name
应始终 return 每个测试的唯一名称 运行。需要注意的是,如果您生成大量数字,它可能 运行 超出唯一值并引发错误。
您还必须在测试 运行 之间清除数据库,否则可能会产生冲突。