Skip to content

Instantly share code, notes, and snippets.

@janpaul123
Created April 8, 2017 17:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janpaul123/1f2ad60d691f85b6bb23e2c9d4ba5a52 to your computer and use it in GitHub Desktop.
Save janpaul123/1f2ad60d691f85b6bb23e2c9d4ba5a52 to your computer and use it in GitHub Desktop.
Assertions
module Assert
class AssertionError < StandardError
end
def self.expect(value)
raise 'No block with error message given to Assert.expect' unless block_given?
# In tests make sure that the assertion parameters are correct. This is a
# bit slower, but prevents errors in assertions.
return if value && !Rails.env.test?
error_data = yield
case error_data
when String
message = error_data
extra = {}
when Hash
message = error_data.fetch(:message)
extra = error_data.dup
extra.delete(:message)
else
raise 'Assert.expect block may only return a String or Hash'
end
return if value # Again, for in tests.
if Rails.env.development? || Rails.env.test?
message += " | extra: #{extra.inspect}" unless extra.empty?
raise AssertionError, message
else
# Prevent spamming Sentry many times from the same request.
RequestStore.store[:assert_expect_messages_sent] ||= {}
if RequestStore.store[:assert_expect_messages_sent][message].nil?
RequestStore.store[:assert_expect_messages_sent][message] = true
Raven.capture_message(message, extra: extra, level: 'warning')
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment