Skip to content

Instantly share code, notes, and snippets.

@paulkoegel
Last active December 22, 2015 06:09
Show Gist options
  • Save paulkoegel/6429042 to your computer and use it in GitHub Desktop.
Save paulkoegel/6429042 to your computer and use it in GitHub Desktop.
module Slug
def generate_slug
temp_slug = SecureRandom.hex 8
# ensure slug is unique
while self.class.where(slug: temp_slug).count > 0
temp_slug = SecureRandom.hex 8
end
self.slug = temp_slug
end
end
require 'spec_helper'
class Abc < OpenStruct
include Slug
@@instances = []
def initialize(attributes = {})
super(attributes)
@@instances << self
end
def self.where(attributes)
@@instances.find_all do |instance|
attributes.all? do |key, value|
instance.send(key) == value
end
end
end
end
describe Slug do
let(:object) { Abc.new }
let(:hex_regex) { /\A[\d|abcdef]{16}\z/ }
before do
#object.stub_chain(:class, :where, :count).and_return(
end
describe 'generate_slug' do
context 'normal behaviour' do
before do
SecureRandom.should_receive(:hex).once.and_return('0123456789abcdef')
end
specify do
expect(object.generate_slug).to match hex_regex
end
end
context 'duplicate slug' do
let!(:other_object) { Abc.new(slug: '153d0849b8c7ac74') }
before do
# second value of and_return will be returned on second call of .hex
SecureRandom.should_receive(:hex).twice.and_return other_object.slug, '0123456789abcdef'
object.generate_slug
end
specify do
expect(object.slug).to_not eql other_object.slug
expect(object.slug).to match hex_regex
end
end
end
end
require 'spec_helper'
describe Slug do
let(:klass) { Class.new { include Slug; attr_accessor :slug } }
let(:object) { klass.new }
let(:hex_regex) { /\A[\d|abcdef]{16}\z/ }
describe 'generate_slug' do
context 'normal behaviour' do
before do
klass.stub_chain(:where, :count).and_return 0
SecureRandom.should_receive(:hex).once.and_return('0123456789abcdef')
object.generate_slug
end
specify do
expect(object.slug).to match hex_regex
end
end
context 'duplicate slug' do
before do
klass.stub_chain(:where, :count).and_return 1, 0
# second value of and_return will be returned on second call of .hex
SecureRandom.should_receive(:hex).twice.and_return '111222333444555a', '0123456789abcdef'
object.generate_slug
end
specify do
expect(object.slug).to_not eql '111222333444555a'
expect(object.slug).to match hex_regex
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment