Last active
March 1, 2017 19:04
-
-
Save maxehmookau/102dc4b52663e731058fbf82b2504cee to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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 | |
This file contains hidden or 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
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 |
This file contains hidden or 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
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