【问题标题】:testing for method_defined? on ActiveRecord classes doesn't work until an instantiation测试方法定义? ActiveRecord 类在实例化之前不起作用
【发布时间】: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


    【解决方案1】:

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

    Inconsistent method_defined? behaviour

    我找到了 .attribute_method?在课堂上工作以做你需要的事情。您可以在ActiveRecord::AttributeMethods::ClassMethods 找到更多信息

    【讨论】:

    • 非常感谢! .attribute_method? 解决问题!
    猜你喜欢
    • 2011-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-10
    相关资源
    最近更新 更多