简体   繁体   English

如何测试视图助手呈现局部视图?

[英]How to test that a view helper renders a partial?

Say I want to render different partials depending on an instance variable from the controller. 说我想根据控制器的实例变量渲染不同的局部。 I put the logic in a helper method, that looks something like: 我将逻辑放在辅助方法中,如下所示:

def display_my_partial(foo)
  foo == bar ? render(partial_x) : render(partial_y)
end

and in the view I call (using Slim): 并在视图中调用(使用Slim):

= display_my_partial(@foo)

What should my test look like? 我的测试应该是什么样的? I tried something like: 我尝试了类似的东西:

expect(display_my_partial(foo)).to render(partial: 'partial_x')

but got: 但得到:

NoMethodError:
       undefined method `matches?' for #<ActiveSupport::SafeBuffer:0x007ffb490aba80>

My example is a bit more complicated, as my partials are in a nested namespace. 我的示例有点复杂,因为我的局部变量位于嵌套的名称空间中。 I had to experiment a little with just usind render 'partial_x' vs render partial: 'namespace/model/partial_x' to get it working in the specs, but finally I got the above mentioned error. 我不得不尝试一点只有usind render 'partial_x' VS render partial: 'namespace/model/partial_x'得到它的规范工作,但最后我得到了上述的错误。

So how would you test this? 那么您将如何测试呢?

Where are you testing it in? 您在哪里进行测试? Make sure render_views is called. 确保调用render_views。

In any case, do you really care it's rendering that partial? 无论如何,您是否真的在乎它呈现了那部分? What if the file name is changed, or you decide to change the implementation using html helpers instead. 如果更改了文件名,或者您决定使用html helper更改实现,该怎么办。 None of this matters to the output. 这与输出无关。 I would personally assert the output instead. 我个人将断言输出。 Depending on how complex the output is you could do it in a view test or just simple unit tests. 根据输出的复杂程度,您可以在视图测试或简单的单元测试中进行输出。

HTH, HTH,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM