测试method_defined?在实例化之前,ActiveRecord类不起作用

dea*_*ane 3 unit-testing ruby-on-rails

我在测试与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
Run Code Online (Sandbox Code Playgroud)

显然有一些ActiveRecord生命周期工作正在进行,作为.new()的先决条件,它将所有数据库列作为方法添加到类中.

在单元测试期间,这确实使事情变得复杂.我想要一个在运行时接受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
Run Code Online (Sandbox Code Playgroud)

我可以做什么来断言(除了使用.new()创建一个垃圾实例)ActiveRecord已经完成初始化?

Eri*_*all 6

这似乎是一个错误,但不太可能很快修复.

method_defined不一致?行为

我发现.attribute_method?在课堂上工作,做你需要的.您可以在ActiveRecord :: AttributeMethods :: ClassMethods中找到更多信息