Created
March 21, 2012 20:16
-
-
Save johncblandii/2152420 to your computer and use it in GitHub Desktop.
Need factory to auto-create an invitation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#USER MODEL [just the relevant parts] | |
has_many :sent_invitations, :class_name=>"Invitation", :foreign_key=>:sender_id | |
validate :check_for_invitation, :on=>:create | |
private | |
def check_for_invitation | |
errors.add :email, 'has not been invited' unless Gxtended::Invitation.where(:recipient_email=>email).exists? | |
end | |
#INVITATION MODEL | |
class Invitation < ActiveRecord::Base | |
belongs_to :sender, :class_name => "User" | |
validates :sender, :presence => true | |
validates :recipient_email, :presence => true, :uniqueness=>true | |
validate :recipient_is_not_registered | |
before_create :generate_token, :only=>[:create] | |
before_create :set_sent_at, :only=>[:create] | |
private | |
def generate_token | |
self.token = Digest::SHA1.hexdigest([Time.now, rand].join) | |
end | |
def recipient_is_not_registered | |
errors.add :recipient_email, 'is already registered' if Gxtended::User.find_by_email(recipient_email) | |
end | |
def set_sent_at | |
sent_at = Time.now | |
end | |
end | |
#SAMPLE FROM SPECS | |
before(:each) do | |
@user = FactoryGirl.create(:user) | |
@admin = FactoryGirl.create(:admin) | |
@url = FactoryGirl.create(:url) | |
end | |
#FACTORIES | |
factory :invite, :class => Gxtended::Invitation do | |
recipient_email "[email protected]" | |
end | |
factory :admin, :class => Gxtended::User do | |
sequence(:username) { |n| "admin#{n}" } | |
sequence(:email) { |n| "admin#{n}@example.com" } | |
password 'password' | |
password_confirmation { |u| u.password } | |
dob "1980-01-01" | |
role { Gxtended::Role[:admin] } | |
end | |
factory :user, :class => Gxtended::User do | |
sequence(:username) { |n| "username#{n}" } | |
sequence(:email) { |n| "user#{n}@example.com" } | |
password 'password' | |
password_confirmation { |u| u.password } | |
dob "1980-01-01" | |
end |
jwo
commented
Mar 21, 2012
via email
Awesome!
- jesse
…On Mar 21, 2012, at 5:25 PM, "John C. Bland II" ***@***.*** wrote:
Finished in 22.69 seconds
132 examples, 0 failures
Woot! :-) Since my invitation factory used a static email address, that spec worked just fine as well without interfering with the other invites for admin users. :) Good stuff.
---
Reply to this email directly or view it on GitHub:
https://gist.github.com/2152420
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment