Specifying minimum length when using FFaker::Internet.user_name

ぐ巨炮叔叔 提交于 2019-12-24 17:07:35

问题


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

How do I specify a minimum length in this stmt:

username { FFaker::Internet.user_name }

回答1:


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

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

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

for example

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



回答2:


You can't, but you could do FFaker::Name.name.join, this generates first name and middle name




回答3:


There're many ways you can achieve this, but if I had to do it, I'd do something like

(FFaker::Internet.user_name + '___')[0...5]
#=> "Lily_"

There are three underscores because after the quick lookup to the name list, I found the minimum length of first name is two characters so two plus three will always be at least five characters.

I'm only taking five character substring so as to not always have trailing underscore, but that's just my personal preference, you can use username plus three underscores and your test case will do fine.



来源:https://stackoverflow.com/questions/51071115/specifying-minimum-length-when-using-ffakerinternet-user-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!