通过 RSpec 测试时将直接参数传递给 Controller#method
通常,要通过 RSpec 传递参数,我们会这样做:
params[:my_key] = my_value
get :my_method
其中 my_method
处理从 params 接收到的内容。但在我的控制器中,我有一个方法,它直接接受参数,即:
def my_method(*args)
...
end
如何从测试中使用这些参数调用该方法?我尝试过 get :my_method(args)
但 Ruby 解释器抱怨语法错误。
Normally to pass parameters via in RSpec we do:
params[:my_key] = my_value
get :my_method
Where my_method
deals with what it received from params. But in my controller I have a method, which takes args directly i.e.:
def my_method(*args)
...
end
How do I call the method with those args from within the test? I've tried get :my_method(args)
but Ruby interpreter complains about syntax error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我所知,你不能这样做。如果您需要直接测试
my_method
,您可以将my_method
提取到帮助程序或库中,然后使用 Rspec 进行测试。或者,您可以构建控制器测试,以便将my_method
中的代码作为控制器操作的一部分来执行,该操作可以由标准 HTTP 动词(get、post、put、delete)之一调用。最终,必须能够通过使用
get
、post
等设置测试来访问控制器使用的任何代码,否则 Rails 无法做到这一点,您的应用程序也无法做到这一点行不通的。这可能会让测试变得不方便,但它也可能告诉您,my_method
最好生活在控制器之外。As far as I can see, you can't do that. You can extract
my_method
into a helper, or into a library, and then test it with Rspec, if you need to testmy_method
directly. Or you can structure your controller tests so that the code inmy_method
is exercised as part of a controller action that can be called by one of the standard HTTP verbs (get, post, put, delete).Ultimately it has to be possible to reach any code that your controller uses by setting up tests with
get
,post
, etc, because otherwise Rails couldn't do it and your app wouldn't work. This may make testing inconvenient, but it might also be telling you thatmy_method
would be better off living outside the controller.