Skip to content

Instantly share code, notes, and snippets.

@maxehmookau
Last active March 1, 2017 19:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxehmookau/102dc4b52663e731058fbf82b2504cee to your computer and use it in GitHub Desktop.
Save maxehmookau/102dc4b52663e731058fbf82b2504cee to your computer and use it in GitHub Desktop.
class Organisation < ApplicationRecord
NUMBER_OF_PERMITTED_USERS = 10
has_many :users, before_add: :validate_user_limit
private
def validate_user_limit(user)
raise Exception.new if users.size >= NUMBER_OF_PERMITTED_USERS
end
end
test 'attempting to add more than the permitted number of users to an organisation should fail' do
org = create(:organisation)
assert_raises Exception do
# Adding 11 users should raise an exception but allow the first
# 10 to be added without a problem.
# This assertion catches the exception thrown so that we can run the
# assertion on line 14 without the test erroring.
org.users.push(create_list(:user, 11))
end
# Check that despite attempting to add 11,
# only 10 have been added.
assert_equal 10, org.users.size
end
class User < ApplicationRecord
# The optional: true flag is only for Rails 5 if a User
# doesn't always belong to an organisation.
belongs_to :organisation, optional: true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment