3
我有一个问题测试对应于ActiveRecord的数据库列的方法。就拿你有(在我的案例文档)的任何模型,然后执行以下操作:测试method_defined?在ActiveRecord类不工作,直到实例化
$ rails c
Loading development environment (Rails 3.0.9)
>> Document.method_defined?(:id)
=> false
>> Document.new
=> #<Document id: nil, feed_id: nil >
>> Document.method_defined?(:id)
=> true
显然有一些ActiveRecord的生命周期的工作仍在进行中,一个先决条件。新的(),这是将所有的数据库列,方法的类。
在单元测试过程中,这确实使事情复杂化。我想有一个在运行时接受的ActiveRecord类和做对他们的一些验证类
例如
class Foo < ActiveRecord::Base
def work1
# something
end
end
class Command
def operates_on(clazz, method)
# unless I add a "clazz.new" first, method_defined? will fail
# on things like :id and :created_at
raise "not a good class #{clazz.name}" if ! clazz.method_defined?(method)
# <logic here>
end
end
describe Command do
it "should pass if given a good class" do
Command.new.operates_on(Foo,:work1)
end
it "should pass if given a database column" do
# this FAILS
Command.new.operates_on(Foo,:id)
end
it "should raise if given an invalid class/method combo" do
lambda { Command.new.operates_on(Foo,:non_work) }.should raise_error
end
end
我能做些什么断言(不是制造垃圾实例与其他。新的() )ActiveRecord已经完成了它的初始化?
找到更多信息非常感谢! '.attribute_method?'解决了问题! – phlegx