Skip to content

Instantly share code, notes, and snippets.

@jiggneshhgohel
Last active October 29, 2016 21:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jiggneshhgohel/d4d5996207dcf81bef8e to your computer and use it in GitHub Desktop.
Save jiggneshhgohel/d4d5996207dcf81bef8e to your computer and use it in GitHub Desktop.
FactoryGirl - Generate a Random Mac Address

Can be useful in generating fake MAC addresses while writing specs for a class which has a MAC address attribute.

FactoryGirl.define do
  sequence :mac do |n|
    12.times.map { num = (0..15).to_a.sample; num.to_s(16) }.each_slice(2).to_a.map { |arr| arr.join('') }.join(":").upcase
  end
end

Sample Output

90:A2:EE:23:BC:EA

@minyoung
Copy link

Instead of generating a nibble at a time and have to deal with combining the nibbles into a byte, how about generating the entire byte?

6.times.map { '%02x' % rand(0..255) }.join(':')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment