从工厂女孩返回模拟对象
我在 JRuby Rails 应用程序中使用 Mocha 和 Factory_girl。 当我调用工厂时,我想返回已经完成一些模拟的对象。 这是我正在尝试做的事情的代码片段。
Factory.define :tweet_feed_with_tweets, :parent => :tweet_feed do |t|
t.expects(:pull_tweets).returns([Factory.build(:status),Factory.build(:status)])
end
因为我不希望我的单元和功能测试实际从 twitter API 中提取,所以我想存根该方法,以便它返回我想要的内容。 但是,这不起作用。 该对象返回时没有完成任何存根。 有没有一种方法可以在工厂女孩创建的对象返回给您之前对其进行存根操作?
I am using Mocha and Factory_girl in a JRuby rails application. When I call the factory I would like to return the objects with some mocking already done. Here is a code snippet of what I am trying to do.
Factory.define :tweet_feed_with_tweets, :parent => :tweet_feed do |t|
t.expects(:pull_tweets).returns([Factory.build(:status),Factory.build(:status)])
end
Because I do not want my unit and functional test to actually pull from the twitter API i want to stub the method so it returns what I want. But, this is not working. The object comes back without any stubbing done. Is there a way to actually have stubbing performed on an object created with factory girl before it gets returned to you?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
回调现已可用:
Callbacks are now available:
查看文档&
factory_girl
的源代码,看起来生成到块的对象(t
,在您的示例中)是Factory
的实例,而不是您要构造的对象的实例(在您的示例中为tweet_feed_with_tweets
)。 这意味着在t
上为pull_tweets
方法设置期望是在Factory
实例上设置期望,而不是在将构造的对象上设置期望当您调用Factory(:tweet_feed_with_tweets)
时。 我认为这解释了为什么你的例子没有按你的预期工作。我可能是错的,但我看不到在
Factory.define
块中添加期望的方法。 您可能已经想到了这一点,但我认为您最好在构建实例后在测试中添加期望:-如果您在多个地方需要它,您可以将其提取到方法中:-
其他一些想法:-
pull_tweets
方法(以及任何类似的方法)分离到TwitterAPI
类中可能是值得的。 这样,看起来就不会那么糟糕,以至于您需要在测试中对TwitterAPI
设置期望。我希望其中一些有所帮助。
Looking at the documentation & source code for
factory_girl
, it looks like the object yielded to the block (t
, in your example) is an instance of aFactory
and not an instance of the object you want to construct (thetweet_feed_with_tweets
, in your example). This means that setting an expectation for thepull_tweets
method ont
is setting the expectation on theFactory
instance and not on the object that will be constructed when you callFactory(:tweet_feed_with_tweets)
. I think this explains why your example is not working as you expect.I may be wrong, but I can't see a way of adding the expectation within the
Factory.define
block. You've probably already thought of this, but I think you'd be better off adding the expectation in the test after you've constructed the instance :-If you need this in multiple places, you can extract it into a method :-
A couple of other thoughts :-
stubs
was more appropriate thanexpects
.pull_tweets
method (and any similar methods) into aTwitterAPI
class. That way it wouldn't seem so bad that you need to set up an expectation on theTwitterAPI
in the test.I hope some of that helps.