分解您的 RSpec 测试

发布于 2024-12-21 13:10:32 字数 481 浏览 5 评论 0原文

我的一些 Rspec 测试已经变得非常非常大(2000-5000 行)。我只是想知道是否有人尝试过将这些测试分解为满足以下条件的多个文件:

  • 有一种命名和放置测试的系统方法(例如方法 AL 转到 user_spec1.rb)。
  • 您可以运行一个文件,该文件将实际运行其他文件中的其他测试。
  • 您仍然可以在文件中运行特定的上下文
  • ,而且很高兴的是,RubyMine 可以很好地运行特定的测试(以及所有测试)。

目前,我已经成功地做到了

#user_spec.rb
require 'spec_helper'
require File.expand_path("../user_spec1.rb", __FILE__)
include UserSpec

#user_spec1.rb
module UserSpec do
  describe User do
    ..
  end
end

Some of my Rspec tests have gotten really really big (2000-5000 lines). I am just wondering if anyone has ever tried breaking these tests down into multiple files that meet the following conditions:

  • There is a systematic way of naming and placing your test (e.g. methods A-L gos to user_spec1.rb).
  • You can run a single file that will actually run the other tests inside other files.
  • You can still run a specific context within a file
  • and, good to have, RubyMine can run a specific test (and all tests) just fine.

For now, I have been successful in doing

#user_spec.rb
require 'spec_helper'
require File.expand_path("../user_spec1.rb", __FILE__)
include UserSpec

#user_spec1.rb
module UserSpec do
  describe User do
    ..
  end
end

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

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

发布评论

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

评论(1

忆梦 2024-12-28 13:10:32

如果你的规格变得太大,那么你的模型也可能太大——因为你在这里使用了“UserSpec”,你可以说你的用户类是“神级"。也就是说,它做得太多了。

因此,我会将其分解为更小的类,每个类都有一个职责。然后,单独测试这些类。

您可能会发现,您的 User 类知道如何执行系统中的大多数逻辑——这是一个很容易陷入的陷阱,但如果您将逻辑放在一个将用户作为参数的类中,则可以避免。另外,如果您坚定地遵循德米特法则(您的用户类别只能触及其下一级,但不能二级)。

进一步阅读:http://blog.rubybestpractices.com/posts/gregory/055 -issue-23-solid-design.html

If your specs are getting too big, it's likely that your model is too big as well -- since you used "UserSpec" here, you could say your user class is a "God class". That is, it does too much.

So, I would break this up into much smaller classes, each of which have one single responsibility. Then, test these classes in isolation.

What you may find is that your User class knows how to execute most logic in your system -- this is an easy trap to fall into, but can be avoided if you put your logic in a class that takes a user as an argument... Also if you steadfastly follow the law of demeter (where your user class could only touch 1 level below it, but not two).

Further Reading: http://blog.rubybestpractices.com/posts/gregory/055-issue-23-solid-design.html

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