我在测试与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 …Run Code Online (Sandbox Code Playgroud) 如何在Rails 4中找到为控制器定义的控制器方法?我环顾四周,Rails.application找到定义的命名路由,但不是定义的方法.