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

Allow unique values to be cleared #810

Merged
merged 2 commits into from
Feb 4, 2017
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
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,15 @@ Prefix your method call with `unique`. For example:
Faker::Name.unique.name # This will return a unique name every time it is called
```

If too many unique values are requested from a generator that has a limited
number of potential values, a `Faker::UniqueGenerator::RetryLimitExceeded`
exception may be raised. It is possible to clear the record of unique values
that have been returned, for example between tests.
```ruby
Faker::Name.unique.clear # Clears used values for Faker::Name
Faker::UniqueGenerator.clear # Clears used values for all generators
```

## Customization

Since you may want to make addresses and other types of data look different
Expand Down
8 changes: 8 additions & 0 deletions lib/helpers/unique_generator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,13 @@ def method_missing(name, *arguments)
end

RetryLimitExceeded = Class.new(StandardError)

def clear
@previous_results.clear
end

def self.clear
ObjectSpace.each_object(self, &:clear)
end
end
end
26 changes: 26 additions & 0 deletions test/test_faker_unique_generator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,30 @@ def stubbed_generator.test
end
end

def test_clears_unique_values
stubbed_generator = Object.new
def stubbed_generator.test
1
end

generator = Faker::UniqueGenerator.new(stubbed_generator, 3)

assert_equal(1, generator.test)

assert_raises Faker::UniqueGenerator::RetryLimitExceeded do
generator.test
end

Faker::UniqueGenerator.clear

assert_equal(1, generator.test)

assert_raises Faker::UniqueGenerator::RetryLimitExceeded do
generator.test
end

generator.clear

assert_equal(1, generator.test)
end
end