在 Ruby on Rails 应用程序中使用 RSpec 时,对 Mock 对象的 #class 方法进行存根是否合法?
我想对模拟对象的 #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 方法的用途?
I would like to stub the #class method of a mock object:
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
On line 5 of this program, I stub the #class method, in order to allow things like @john.class.name. Is this the right way to go? Will there be any bad side effect?
Edit:
The Letter class looks like this:
class Letter < ActiveRecord::Base
belongs_to :to, :polymorphic => true
[...]
end
I wonder whether ActiveRecord gets the :to field's class name with to.class.name
or by some other means. Maybe this is what the class_name method is ActiveRecord::Base is for?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为对于这种特殊情况,您应该使用
mock_model
。你的
before(:each)
看起来像这样:那么对于你的另一个问题,你不应该真正关心 Rails 如何测试你的行为。 我认为自己测试 to_type 和 to_id 字段不是一个好主意。 这是 Rails 行为,因此应该在 Rails 中测试,而不是在您的项目中。
我已经使用 Remarkable 一段时间了,它使得指定变得非常容易:
I think you should be using
mock_model
for this particular case.Your
before(:each)
would look like that:Then for your other question, you should not really care about how Rails works to test your behaviour. I don't think it's a good idea to test to_type and to_id fields yourself. This is Rails behaviour and as such should be tested in Rails, not in your project.
I have been using Remarkable for a while and it makes this really easy to specify: