如何添加将调用辅助方法的摩卡咖啡期望? [英] How do I add a mocha expectation that a helper method will be called?

查看:106
本文介绍了如何添加将调用辅助方法的摩卡咖啡期望?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一种方法从控制器转移到帮助器中;现在将从视图中调用该方法.以前,在我的控制器中,我有

I'm moving a method from a controller into a helper; the method will now be called from the view. Previously, in my controller I had

def show
  @things = gather_things
end

在我的功能测试中,

test "show assigns things" do
  get :show
  assert_equal GATHERED_THINGS, assigns(:things)
end

现在,gather_things驻留在助手中,并从视图中调用.我对助手进行了单元测试,以确保其返回正确的值,但是我希望我的功能测试断言它被调用了.我已经尝试过

now, gather_things lives in the helper and is called from the view. I have a unit test for the helper which makes sure that it returns the right values, but I want my functional test to assert that it gets called. I've tried

test "show calls gather_things" do
  @controller.expects(:gather_things)
  get :show
end

但这不起作用.我应该打什么电话expects(:gather_things)?

but that doesn't work. What should I be calling expects(:gather_things) on?

推荐答案

如果您已将代码从控制器中移出到视图中,则实际上它已从功能测试的范围中移出.

If you have moved the code out of the controller into a View then it has in fact moved out of the purview of the functional test.

我不知道可以期望的正确类...但是您可能可以通过在"gather_things"方法中执行以下操作来弄清楚它:logger.error self.class.name-这将把类名吐出来您的日志.然后,您可以将期望值放在该类上.

I don't know the correct class to put your expects on... but you can probably figure it out by, in the method "gather_things" do something like: logger.error self.class.name - which will spit out the class name into the log for you. Then you can put your expects onto that class.

现在我们进入问题的症结所在……您是否应该将该代码移入视图?

Now we come to the crux of the matter... should you have moved that code into the view?

我认为您不应该这样做.设置模型对象的集合正是应该在控制器代码中执行的操作-如果您以后决定要在CSV文件或RESTful xml API中显示相同的数据,该怎么办? -无论使用哪种视图,您仍然都需要实例化相同的对象集.因此,我的最终建议是将该方法再次移回它所属的控制器中.

My opinion is that you should not. Setting up a gathering of model-objects is precisely what is supposed to go in the controller code - what if you later decide you want to display the same data in a CSV file, or as a RESTful xml API? - you still need the same set of objects instantiated regardless of what view you use. So my Ultimate Recommendation would be to move that method back into the controller again where it belongs.

以下建议已过时,与该用户无关,但可能与其他用户无关

following is now obsolete advice and not relevant to this user, but might be to others

如果您正在使用rspec进行测试-它实际上不会在功能测试期间渲染视图(除非您专门将其打开),因此将不执行任何称为表单视图的代码.

If you are testing using rspec - it doesn't actually render the views during a functional test (unless you specifically switch that on), and therefore any code called form views will not execute.

如果要测试View是否调用了某些东西,则需要将其打开或在视图测试中对其进行测试.

If you want to test that the View calls something, you will either need to turn that on, or test it in your view-tests.

这篇关于如何添加将调用辅助方法的摩卡咖啡期望?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆