【发布时间】:2011-11-04 17:58:54
【问题描述】:
我在测试与 ActiveRecord 的数据库列相对应的方法时遇到问题。采用您拥有的任何模型(在我的情况下为 Document),然后执行以下操作:
$ 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
作为 .new() 的先决条件,显然有一些 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 已经完成了初始化(除了使用 .new() 创建一个垃圾实例)?
【问题讨论】:
标签: ruby-on-rails unit-testing