控制器规格与请求规格?

Controller Specs vs Request Specs?

我正在研究 rails API,我现在正计划为控制器编写一些 RSpec 测试。 我一直在四处阅读,但一直无法弄清楚控制器规格和请求规格之间的实际区别是什么,以及如果我正在测试 API.[=10= 我应该使用哪一个。 ]

Rails 3 & 4

控制器规格 - 控制器规格是 RSpec 包装器,用于 Rails 功能测试。它允许您在每个示例中模拟单个 http 请求,然后 指定预期结果

请求规范 - 请求规范提供了一个围绕 Rails 集成测试的薄包装,并且是 旨在通过整个堆栈驱动行为,包括路由 (由 Rails 提供)并且没有存根(由您决定)。

因此,如果您想测试 API 个控制器,我建议您在测试单个请求时使用 Controller specs


Rails 5+

Rails 5 比 Rails 版本 4 的控制器和请求规范提高了 请求规范 的速度和真实性。 The official recommendation of the Rails team and the RSpec core team is to write request specs instead (of controller specs).

引用亚伦·萨姆纳的话:

Both the Rails and RSpec teams suggest replacing or removing your app’s controller tests (also known as the functional test layer), in favor of directly testing models (units), or with higher-level integration tests.

对于新的 API,与使用控制器测试相比,我更喜欢使用请求规范并点击我的 "end points"(又名模型和业务逻辑)。

确实,RSpec 团队正式声明 控制器规格现已过时

http://rspec.info/blog/2016/07/rspec-3-5-has-been-released/

For new Rails apps: we don't recommend adding the rails-controller-testing gem to your application. The official recommendation of the Rails team and the RSpec core team is to write request specs instead. Request specs allow you to focus on a single controller action, but unlike controller tests involve the router, the middleware stack, and both rack requests and responses. This adds realism to the test that you are writing, and helps avoid many of the issues that are common in controller specs. In Rails 5, request specs are significantly faster than either request or controller specs were in rails 4, thanks to the work by Eileen Uchitelle1 of the Rails Committer Team.