Skip to content

Instantly share code, notes, and snippets.

@trueheart78
Last active July 9, 2024 15:37
Show Gist options
  • Save trueheart78/ef9f6903d42dc2a2bcd4a38be571f10e to your computer and use it in GitHub Desktop.
Save trueheart78/ef9f6903d42dc2a2bcd4a38be571f10e to your computer and use it in GitHub Desktop.

Revisions

  1. trueheart78 revised this gist Jul 9, 2024. 1 changed file with 2 additions and 1 deletion.
    3 changes: 2 additions & 1 deletion junklet.rb
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,6 @@
    # All credit to Dave Brady & his RSpec-Junklet Project that changed how I think about test data.
    # https://rubygems.org/profiles/dbrady
    # * 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)
  2. trueheart78 created this gist Jul 9, 2024.
    32 changes: 32 additions & 0 deletions junklet.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    # All credit to Dave Brady & his RSpec-Junklet Project that changed how I think about test data.
    # https://rubygems.org/profiles/dbrady

    # 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