I’ve been developing a series of custom assertions for testing my models
and it
looks like I can unify most some of the assertions if I can find a good
way to
determine the class under test at run-time. Now I refactor my test code
rather
vigorously so its not as simple as just stripping “Test” off the name of
the
test case class, but I have a few thoughts on a useful convention I can
use to
ease it.
Now this is probably more of a (near novice) Ruby question rather than
rails,
but I can’t seem to locate the answer – given a string containing a
class name
is there a way to
a) check if that class is defined/locatable for inclusion
b) convert the string to a Class object for the named class
Ie, I’m trying to do:
def setup
@klass=class_under_test(self.class)
end
protected
def class_under_test(klass)
/([A-Z][a-z_]*)Test/.match(klass.to_s)
$1 # <----- Now I have a string, not a Class, obviously
# Of course I need a more complete alogrithm here, but I’d like
to
# to get the base case working first, do I need to use one of the
# eval-type functions?
end
def assert_attribute_required(field)
@non_inserted_fixture[field]=nil
obj = @klass.new(@non_inserted_fixture) # <---- Now I need a Class
object
assert_not_valid obj
assert obj.errors.invalid?(field)
end
Thank you.
Eric
I am not sure if I get your question right… maybe this is what you
need:
require ‘set’
def acts_as_test
TestClasses.get << self
end
class TestClasses
@@test_classes = Set.new
def self.get
@@test_classes
end
end
class TestMe
acts_as_test
end
class TestMeToo
acts_as_test
end
TestClasses.get.inspect
#<Set: {TestMeToo, TestMe}>
-------- Original-Nachricht --------
Datum: Tue, 13 Jun 2006 10:14:54 -0400
Von: Eric D Nielsen [email protected]
An: [email protected]
Betreff: [Rails] Dynamic determination of class under test…
def assert_attribute_required(field)
@non_inserted_fixture[field]=nil
obj = @klass.new(@non_inserted_fixture) # <---- Now I need a Class
object
assert_not_valid obj
assert obj.errors.invalid?(field)
end
For this part, thanks to ActiveSupport, you would have something like:
…
obj = @klass.constantize.new()
…
That will get you your new class object to work with.
Thank you.
Nick S. wrote:
def assert_attribute_required(field)
@non_inserted_fixture[field]=nil
obj = @klass.new(@non_inserted_fixture) # <---- Now I need a Class
object
assert_not_valid obj
assert obj.errors.invalid?(field)
end
For this part, thanks to ActiveSupport, you would have something like:
…
obj = @klass.constantize.new()
…
Thank you, that was one half of what I was looking for and I’m
positively I can figure out the rest now that the base case works.
Eric