Skip to content

Commit

Permalink
Allow unique values to be cleared (#810)
Browse files Browse the repository at this point in the history
  • Loading branch information
dslh authored and stympy committed Feb 4, 2017
1 parent c21aff7 commit fbe2083
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,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

0 comments on commit fbe2083

Please sign in to comment.