我应该如何在 Rails 中测试这个?

发布于 2024-12-17 10:30:13 字数 181 浏览 4 评论 0原文

我正在为我的模型中的方法编写测试。当然,听起来我需要单元测试,但是此方法的参数之一从 Rails 应用程序中的表单获取参数。我应该创建单元测试或功能测试(或两者)?

对于单元测试,我只是将参数变量设置为类似于表单响应的输出的哈希值,但是我想知道这是否是最好的方法,因为表单参数可以在将来的某个时候更新或更改。

谢谢。

I'm writing tests for a method in my model. Of course it sounds like I need unit tests, however one of this method's arguments takes the parameters from a form in the rails app. Should I create unit tests or functional tests (or both)?

For the unit tests, I'm just setting a param variable to a hash similar to the output from the form response, however I'm wondering if that's the best approach since the form params could be updated or changed sometime in the future.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谁许谁一生繁华 2024-12-24 10:30:13

您的方法至少应该有一个或多个单元测试。一般来说,您需要涵盖三件事:

  1. 基本情况 - 最有可能为此方法提供的参数是什么?
  2. 特殊情况——哪些极端情况仍然会过去?上限和下限是多少?空的情况怎么办?
  3. 无效情况 - 哪些值可能提供给无效的方法?你的方法如何处理它们?

如果您涵盖了这些情况,并且没有做任何特殊的事情来将参数传递给方法,那么功能测试就变得不那么重要了。

不过,我仍然鼓励您进行一些行为测试。 Rails 是一种可以轻松完成单元测试和行为/集成测试的环境,因为有很多可用的 gem - 主要是 RSpec黄瓜水豚。如果您编写 Cucumber 功能,那么 Capybara 将获取表单参数更改,如果有任何问题,您的功能将失败。

You should at minimum have one or more unit tests for your method. Generally you need to cover three things:

  1. The base case - What are the most likely parameters to be given to this method?
  2. The special cases - What are the extreme cases that will still pass? What are the upper and lower bounds? What about the null case?
  3. The invalid cases - What values possibly can be provided to the method that are invalid? How does your method deal with them?

If you cover those cases and you aren't doing anything special with passing the parameters to the method, then the functional test becomes less important.

However I still encourage you to do some behavioural testing. Rails is one environment where both unit testing and behavioural/integration testing are easy to accomplish due to the great gems available - mainly RSpec, Cucumber and Capybara. If you write a Cucumber feature then Capybara will pick up the form parameter changes and your feature will fail if anything is amiss.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文