[英]Is it legal to stub the #class method of a Mock object when using RSpec in a Ruby on Rails application?
我想存根模擬對象的 #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 方法的用途?
我認為您應該在這種特殊情況下使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.