为什么人们不在 Rspec 中访问数据库? [英] Why don't people access database in Rspec?
问题描述
我经常在Rspec中看到使用mock的代码,像这样:
I often see the code which uses mock in Rspec, like this:
describe "GET show" do
it "should find and assign @question" do
question = Question.new
Question.should_receive(:find).with("123").and_return(question)
get :show, :id => 123
assigns[:question].should == question
end
end
但是为什么他们不在数据库中添加一个 id => 123 的 Question
,通过 get
检索它,然后销毁它?这是最佳做法吗?如果我不遵守规则,会不会有不好的事情发生?
But why they don't add a Question
with id => 123 in database, retrieve it by get
, and destroy it? Is this a best practice? If I don't follow the rule, will something bad happen?
推荐答案
当您编写行为测试(或单元测试)时,您试图仅测试代码的特定部分,而不是整个堆栈.
When you write a behavioral test (or a unit test), you're trying to test only a specific part of code, and not the entire stack.
为了更好地解释这一点,您只是表达和测试函数 A 应该使用这些参数调用函数 B",因此您正在测试函数 A 而不是函数 B,为此您提供了一个模拟.
To explain this better, you are just expressing and testing that "function A should call function B with these parameters", so you are testing function A and not function B, for which you provide a mock.
这很重要,原因有很多:
This is important for a number of reasons:
- 您不需要在构建代码的每台机器上都安装数据库,如果您开始在公司中使用构建机器(和/或持续集成)处理数百个项目,这一点很重要.
- 你会得到更好的测试结果,因为如果函数 B 被破坏,或者数据库不能正常工作,你不会在函数 A 上测试失败.
- 您的测试运行得更快.
- 在每次测试之前拥有一个干净的数据库总是很痛苦的.如果之前运行的测试被停止,在数据库上留下一个带有该 ID 的问题怎么办?您可能会因为 ID 重复而导致测试失败,而实际上该功能运行正常.
- 在运行测试之前,您需要进行适当的配置.这不是一个令人难以置信的问题,但是如果测试可以开箱即用"运行,而无需配置数据库连接、临时测试文件的文件夹、用于测试电子邮件内容的 SMTP 服务器等,那就更好了……
实际测试整个堆栈的测试称为端到端测试"或集成测试"(取决于它测试的内容).这些也很重要,例如,可以使用一组没有模拟数据库的测试来查看给定的应用程序是否可以安全地运行在与开发期间使用的数据库不同的数据库上,并最终修复包含有问题的 SQL 语句的函数.
A test that actually test the entire stack is called "end to end testing", or "integration testing" (depending on what it tests). These are important as well, for example a suite of tests without mock database can be used to see if a given application can run safely of a different DB than the one used during development, and eventually fix functions that contain offending SQL statements.
这篇关于为什么人们不在 Rspec 中访问数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!