2

我想存根模拟对象的#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 方法的用途?

4

1 回答 1

3

我认为你应该使用mock_model这种特殊情况。你before(:each)看起来像这样:

before(:each) do
  @john = mock_model(Person, :name => "John F.")
  Person.stub!(:find).and_return(@john)
end

然后对于您的另一个问题,您不应该真正关心 Rails 如何测试您的行为。我认为自己测试 to_type 和 to_id 字段不是一个好主意。这是 Rails 的行为,因此应该在 Rails 中进行测试,而不是在您的项目中。

我使用Remarkable已经有一段时间了,它使这很容易指定:

describe Letter
  should_belong_to :to, :polymorphic => true
end
于 2009-04-25T14:42:14.380 回答