本文介绍了使用 FFaker::Internet.user_name 时指定最小长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的规范一直失败,因为 FFaker::Internet.user_name 生成的单词少于 5 个字符.

I have a spec that keeps failing because FFaker::Internet.user_name generates a word that is less than 5 characters.

如何在此 stmt 中指定最小长度:

How do I specify a minimum length in this stmt:

username { FFaker::Internet.user_name }

推荐答案

据我所知,您尝试在工厂中使用 FFaker.当你可以定义序列

From what I see you try to use FFaker in your factory. Why overcomplicate things for your specs, when you could define sequence

sequence(:username) do |n|
   "username-#{n}"
end

但是这个问题是有效的,您可能有一些使用 ffaker 的合法需求,并且有很多方法可以做到.您可以将用户名连接两次,为什么不呢?

But the question is valid and you may have some legitimate needs to use ffaker, and there are many ways to do it. You can just concatenate username twice, why not?

username { FFaker.username + FFaker.username }

或者继续寻找长度最短的用户名:

Or keep looking for a username that length is of minimal lenght:

username do
   do
     name = FFaker.username
   while name.length < 5
   name
end

或者monkeypatch ffaker并自己实现它https://github.com/ffaker/ffaker/blob/0578f7fd31c9b485e9c6fa15f25b3eca724790fe/lib/ffaker/internet.rb#L43//github.com/ffaker/ffaker/blob/0578f7fd31c9b485e9c6fa15f25b3eca724790fe/lib/ffaker/internet.rb#L43 +

Or monkeypatch ffaker and implement it yourself https://github.com/ffaker/ffaker/blob/0578f7fd31c9b485e9c6fa15f25b3eca724790fe/lib/ffaker/internet.rb#L43 + https://github.com/ffaker/ffaker/blob/0578f7fd31c9b485e9c6fa15f25b3eca724790fe/lib/ffaker/name.rb#L75

例如

class FFaker
  def long_username(min_length = 5)
    fetch_sample(FIRST_NAMES.select {|name| name.length >= min_lenght })
  end
end

这篇关于使用 FFaker::Internet.user_name 时指定最小长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 12:10