开发者

How do I add a mocha expectation that a helper method will be called?

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

and in my functional test I had

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

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

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.

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?

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.

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

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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜