我想存根模拟对象的#class 方法:
describe Letter do
before(:each) do
@john = mock("John")
@john.stub!(:id).and_return(5)
@john.stub!(:class).and_return(Person) # is this ok?
@john.stub!(:name).and_return("John F.")
Person.stub!(:find).and_return(@john)
end
it.should "have a valid #to field" do
letter = Letter.create!(:to=>@john, :content => "Hello John")
letter.to_type.should == @john.class.name
letter.to_id.should == @john.id
end
[...]
end
在这个程序的第 5 行,我存根 #class 方法,以便允许像 @john.class.name 这样的东西。这是正确的方法吗?会不会有什么不好的副作用?
编辑:
Letter 类如下所示:
class Letter < ActiveRecord::Base
belongs_to :to, :polymorphic => true
[...]
end
我想知道 ActiveRecord 是否通过to.class.name
或通过其他方式获取 :to 字段的类名。也许这就是 ActiveRecord::Base 的 class_name 方法的用途?