Specifying minimum length when using FFaker::Inter

2019-08-01 08:49发布

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 }

3条回答
地球回转人心会变
2楼-- · 2019-08-01 09:07

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.

查看更多
放我归山
3楼-- · 2019-08-01 09:19

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
查看更多
Evening l夕情丶
4楼-- · 2019-08-01 09:24

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

查看更多
登录 后发表回答