Last active
July 9, 2024 15:37
-
-
Save trueheart78/ef9f6903d42dc2a2bcd4a38be571f10e to your computer and use it in GitHub Desktop.
Junklet RSpec Support File
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# All credit to Dave Brady & his RSpec-Junklet Project that changed how I think about test data. | |
# * https://rubygems.org/profiles/dbrady | |
# Place in rspec/support/junklet.rb and have the rails_helper.rb load it | |
# Returns randomized data for when we don't care *what* the data is. | |
def junk(length = 32) | |
# hex returns length*2 digits, because it returns a 0..255 byte | |
# as a hex pair. But when we want junk, we want *bytes* of | |
# junk. Get (length+1)/2 chars, which will be correct for even | |
# sizes and 1 char too many for odds, so trim off with [0...length] | |
SecureRandom.hex((length + 1) / 2)[0...length] | |
end | |
# Use in context and describe blocks. | |
# Example: | |
# junklet :random_one, :random_two, :random_forty_two | |
def junklet(*args) | |
opts = args.size > 1 && !args.last.is_a?(Symbol) && args.pop || {} | |
names = args.map(&:to_s) | |
separator = opts[:separator] || "_" | |
names = names.map {|name| name.gsub(/_/, separator) } | |
args.zip(names).each do |arg, name| | |
make_junklet arg, name, separator | |
end | |
end | |
# Makes the magic happen for the junklet call in describe and context blocks. | |
def make_junklet(let_name, name, separator) | |
let(let_name) { "#{name}#{separator}#{junk}" } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment