# 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