Skip to content

Instantly share code, notes, and snippets.

@maddiesch
Created April 17, 2015 06:05
Show Gist options
  • Save maddiesch/fb60db5bbade2cb1648a to your computer and use it in GitHub Desktop.
Save maddiesch/fb60db5bbade2cb1648a to your computer and use it in GitHub Desktop.
RSpec Helpers
# In spec/support/presence.rb
RSpec.shared_examples 'presence' do |attrs|
describe 'presence validations' do
attrs.each do |attr|
it "checks presence of #{attr}" do
target = described_class.name.downcase.to_sym
obj = FactoryGirl.build target, attr.to_sym => nil
expect(obj.valid?).to eq false
expect(obj.errors[attr.to_sym].size).to eq 1
end
end
end
end
# Load the support files
Dir["./spec/support/**/*.rb"].sort.each { |f| require f}
# In spec/support/uniqueness.rb
RSpec.shared_examples 'uniqueness' do |objects|
describe 'uniqueness validations' do
objects.each do |attr, creator|
it "checks uniqueness of #{attr}" do
new_value = creator.call
expect(new_value).to_not eq nil
target = described_class.name.downcase.to_sym
obj = FactoryGirl.build target
obj.send("#{attr}=", new_value)
expect(obj.save).to eq true
obj2 = FactoryGirl.build target
obj2.send("#{attr}=", new_value)
expect(obj2.valid?).to be false
expect(obj2.errors[attr.to_sym].size).to eq 1
end
end
end
end
require 'rails_helper'
RSpec.describe User, type: :model do
include_examples 'presence', %w(email)
include_examples 'uniqueness', {
email: -> { Faker::Internet.email }
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment