Rails Test 辅助方法接受 ActionView::Helpers::FormBuilder 对象
我正在尝试为接受表单辅助对象的辅助方法编写测试,有没有办法在测试中创建表单对象?
/app/views/blahs/edit.html.erb
<% form_for :blahs do |blah| %>
<%= my_helper_method(blah) %>
<% end %>
/app/helpers/blahs_helper.rb
def my_helper_method(blah) # # blah is ActionView::Helpers::FormBuilder # do something with the form object here # end
那么在我的测试用例中如何创建表单对象?我仍在使用 Rails 2.3.9。
提前致谢
I'm trying to write a test for a helper method that accepts a form helper object, is there a way to create a form object within the test?
/app/views/blahs/edit.html.erb
<% form_for :blahs do |blah| %>
<%= my_helper_method(blah) %>
<% end %>
/app/helpers/blahs_helper.rb
def my_helper_method(blah) # # blah is ActionView::Helpers::FormBuilder # do something with the form object here # end
So in my test case how do I create the form object? I'm still on Rails 2.3.9.
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先尝试部分使用它,然后再尝试使用助手?除非您正在做一些捏造的“模型”类型的事情,否则部分是重用表单代码并且更易于测试的好方法。
助手在某种程度上用于“查看逻辑”。部分用于显示表单字段,甚至是重复的字段。
它可以帮助您了解您在助手中尝试执行的操作,而您在部分操作中无法执行此操作。
try using it with a partial first, then get fancy with a helper maybe? Unless you are doing some fudged up "Model" type stuff, a partial is a great way to reuse form code and easier to test.
helpers are for "View logic" in a way. partials are for displaying form fields, even ones that repeat.
It could help to see what you are trying to do in a helper that you can't in a partial.
理论上,您可以在帮助程序规范中
require 'action_view/helpers/form_helper'
(位于actionpack中),这将使form_for方法可用。不过,我认为 pjammer 认为您应该质疑您放入 helper_method 中的逻辑是否真的属于那里。如果您告诉我们您想在 helper_method 中完成什么,我们也许可以为您提供不需要传递表单对象的替代方案,这可能是更好的方法。
In theory you could
require 'action_view/helpers/form_helper'
(which lives in actionpack) in your helper spec which will make the method form_for available.However I am with pjammer that you should question whether the logic you're putting in your helper_method really belongs there. If you tell us what you're trying to accomplish in helper_method we may be able to give you alternatives that don't require to pass the form object, which is probably a better approach.