Rails 3 - 模拟/存根 - 测试控制器
我有一个关于测试以下 Rails 代码行的问题:
https://gist.github.com/1289849
在我的测试代码中我有这样的东西(显然不起作用):
https://gist.github.com/1289848
有人可以帮我为此编写正确的测试代码吗?
谢谢
i have a question about testing following line of Rails code:
https://gist.github.com/1289849
in my test code i have something like this(obviously don't works):
https://gist.github.com/1289848
Someone can help me write right test code for this ?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了使测试更容易,您应该将此逻辑移至客户端模型上的类方法。我还假设您的用户模型上有一个
has_many :clients
,这就是您的查询所暗示的内容。类似于:
然后在您的控制器中:
这将允许您在单元测试中进行测试,而不是在集成测试中进行测试。
client_spec.rb:
那么您的集成测试只需存根
search_by_name
方法并返回一组模拟,从而更容易测试。To make testing it easier, you should move this logic to a class method on your Client model. I'm also assuming you have a
has_many :clients
on your user model, which is what your query is implying.Something like:
Then in your controller:
This will allow you to test in a unit test, rather than with an integration test.
client_spec.rb:
Then your integration test could just stub the
search_by_name
method and return a collection of mocks, making it easier to test.