Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Faker::UniqueGenerator - exclude method #1307

Merged
merged 1 commit into from
Jul 14, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,18 @@ Faker::Name.unique.clear # Clears used values for Faker::Name
Faker::UniqueGenerator.clear # Clears used values for all generators
```

You also can give some already used values to the unique generator if you have
collisions with the generated data (i.e: using FactoryBot with random and
manually set values).

```ruby
# Usage:
# Faker::<generator>.unique.exclude(method, arguments, list)

# Add 'azerty' and 'wxcvbn' to the string generator with 6 char length
Faker::Lorem.unique.exclude :string, [6], %w[azerty wxcvbn]
```

### Deterministic Random

Faker supports seeding of its pseudo-random number generator (PRNG) to provide deterministic output of repeated method calls.
Expand Down
7 changes: 7 additions & 0 deletions lib/helpers/unique_generator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,12 @@ def clear
def self.clear
ObjectSpace.each_object(self, &:clear)
end

def exclude(name, arguments, values)
values ||= []
values.each do |value|
@previous_results[[name, arguments]] << value
end
end
end
end
6 changes: 6 additions & 0 deletions test/test_faker_lorem.rb
Original file line number Diff line number Diff line change
Expand Up @@ -114,4 +114,10 @@ def test_paragraph_char_count
paragraph = @tester.paragraph_by_chars(256)
assert(paragraph.length == 256)
end

def test_unique_with_already_set_values
values = ('a'..'z').to_a + ('0'..'9').to_a
@tester.unique.exclude(:character, [], values)
assert_raise(Faker::UniqueGenerator::RetryLimitExceeded) { @tester.unique.character }
end
end