diff --git a/app/models/user.rb b/app/models/user.rb index 86c82f0..340ada8 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -16,4 +16,7 @@ class User < ActiveRecord::Base end end + def add_user_token(token) + user_tokens.find_or_create_by_token(token) + end end diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index 5ebde8c..e3243e1 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -47,4 +47,28 @@ describe User do end end + + describe '#add_user_token' do + before { user.save } + + context "when user doesn't have given token" do + let(:token) { Factory.attributes_for(:user_token)[:token] } + + it 'returns created UserToken' do + ut = user.add_user_token(token) + ut.should be_kind_of(UserToken) + ut.id.should_not be(nil) + end + end + + context "when user doesn't have given token" do + let(:existing_token) { Factory(:user_token, :user => user) } + let(:token) { existing_token.token } + + it 'returns existing UserToken' do + ut = user.add_user_token(token) + ut.should == existing_token + end + end + end end