Skip to content

Instantly share code, notes, and snippets.

@mathieul
Last active December 16, 2015 04:19
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mathieul/5375939 to your computer and use it in GitHub Desktop.
Monitoring SQL assertions and other type
class AssertFortyTwo
include SystemStateAssertion
describe "the Answer to the Ultimate Question of Life, the Universe, and Everything to be 42"
expect 42
def actual
2
end
end
class AssertNoContactInFive9AndInSalesforce
include SystemStateAssertion
describe "the number of contacts both in Five9 and in Salesforce to be 0"
expect 0
def actual
@actual ||= Contact.where(:vcc_name => "five9").where("sf_contact_id IS NOT NULL").count
end
end
class AssertThereAreLeadStatusesToday
include SystemStateAssertion
describe "the number of lead statuses so far today to be greater than 0"
expect { |value| value.to_i > 0 }
query { "select count(ls.id) from lead_statuses ls where ls.created_at > '#{Time.now.to_s(:db)}'" }
end
errors = SystemStateAssertion.verify_all
errors.compact!
puts "#{errors.length} error(s)"
errors.each { |error| puts " - #{error}" }
# => 3 error(s)
# => - Expected the Answer to the Ultimate Question of Life, the Universe, and Everything to be 42, but it is 2.
# => - Expected the number of contacts both in Five9 and in Salesforce to be 0, but it is 10.
# => - Expected the number of lead statuses so far today to be greater than 0, but it is 0.
module SystemStateAssertion
def self.all
@all ||= []
end
def self.included(assertion_klass)
self.all << assertion_klass
assertion_klass.extend(ClassMethods)
end
def self.verify_all
all.map { |assertion_klass| assertion_klass.new.verify }
end
module ClassMethods
attr_reader :label, :expectation, :get_sql
def describe(label)
@label = label
end
def expect(value = nil, &expectation)
@expectation = expectation || Proc.new { |actual| actual == value }
end
def query(&get_sql)
@get_sql = get_sql
end
end
def message
"Expected #{self.class.label}, but it is #{actual}."
end
def verify
message unless self.class.expectation.call(actual)
end
def actual
return @actual if instance_variable_defined?(:@actual)
query = self.class.get_sql.call
result = ActiveRecord::Base.connection.execute(query)
@actual = result.fetch_row.first
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment