本文介绍了如何从 Ruby on Rails 的控制台调用控制器/视图助手方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我加载 script/console
时,有时我想使用控制器或视图助手方法的输出.
有没有办法:
- 模拟请求?
- 根据所述请求从控制器实例调用方法?
- 测试辅助方法,通过所述控制器实例还是其他方式?
解决方案
要调用助手,请使用 helper
对象:
$ ./script/console>>helper.number_to_currency('123.45')=>123,45 雷亚尔"
如果您想使用默认情况下未包含的帮助程序(例如,因为您从 ApplicationController
中删除了 helper :all
),只需包含该帮助程序.
>>包括 BogusHelper>>帮手=>虚假输出"
至于处理控制器,我引用尼克的回答:
>app.get '/posts/1'>响应 = app.response# 你现在有一个很像集成测试的 rails 响应对象>response.body # 获取 HTML>response.cookies # cookie 的哈希值# 等等等等
When I load script/console
, sometimes I want to play with the output of a controller or a view helper method.
Are there ways to:
- simulate a request?
- call methods from a controller instance on said request?
- test helper methods, either via said controller instance or another way?
解决方案
To call helpers, use the helper
object:
$ ./script/console
>> helper.number_to_currency('123.45')
=> "R$ 123,45"
If you want to use a helper that's not included by default (say, because you removed helper :all
from ApplicationController
), just include the helper.
>> include BogusHelper
>> helper.bogus
=> "bogus output"
As for dealing with controllers, I quote Nick's answer:
这篇关于如何从 Ruby on Rails 的控制台调用控制器/视图助手方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!