将 Sinatra 应用程序的测试数据库与开发数据库分开?
作为学习练习,我正在使用 Sinatra、Datamapper 和 RSpec 构建一个练习应用程序。我正在使用 此模板,它基本上是上述所有内容的样板。
我遇到的问题是 RSpec 和 Datamapper 的配置方式,每次运行测试数据库相关功能的规范时,这些测试都会直接更改我的开发数据库而不是测试数据库。
例如,我希望在运行规范的其余部分之前创建一些数据库对象...
before(:all) {
Region.new(:country => "Canada", :country_code => "CA").save
ProductLine.new(:reference => "Molders").save
Product.new(:name => "The Black Molder").save
Cart.new(:price => 25.95).save
}
但是每次我运行 RSpec 时,上述元素都会添加到我的开发数据库中。
为什么不生成测试数据库?如何使测试数据库正常工作?
这看起来与这里的问题非常相似,但 Sinatra 除外而不是 Rails。
如果有任何帮助,可以在此处查看我的代码。
As a learning exercise, I am building a practice app using Sinatra, Datamapper and RSpec. I am using this template, which is basically a boilerplate for all the above.
The problem I am having is that the way RSpec and Datamapper seem to be configured, every time a spec is run that tests Database related functionality, those tests directly change my development database instead of a test database.
For example, I wish to create a few database objects before running the rest of the spec...
before(:all) {
Region.new(:country => "Canada", :country_code => "CA").save
ProductLine.new(:reference => "Molders").save
Product.new(:name => "The Black Molder").save
Cart.new(:price => 25.95).save
}
Yet every time I run RSpec, the above elements get added to my development database.
Why isn't a test database being generated instead? How can I get the test database to work properly?
This appears pretty similar to this issue here, except for Sinatra instead of Rails.
If it's any help, my code can be seen here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在
spec_helper.rb
文件中,您需要my_app.rb
文件,而该文件又需要db.rb
来设置数据库,但会发生这种情况 < em>在调用set :environment, :test
之前,因此configure :test
块不会运行(该环境是当时的默认开发环境)阶段)。当然,在需要 Sinatra 之前,您不能调用
set environment :test
,但您可以设置RACK_ENV
环境变量,Sinatra 在设置其环境时会检查该变量。因此,为了确保您在测试环境中运行,请将其添加到
spec_helper.rb
的顶部(或者在测试开始时的其他位置,但在需要 Sinatra 之前):然后您可以删除
set :environment, :test
行,因为它现在是多余的。这与您引用的其他问题类似,但机架应用使用
RACK_ENV
而不是RAILS_ENV
。In
spec_helper.rb
file you are requiringmy_app.rb
file which in turn requiresdb.rb
to set up your database, but this happens before you callset :environment, :test
, so theconfigure :test
block isn't being run (the environment is the default development at that stage).Of course you can't call
set environment :test
before you require Sinatra, but you can set theRACK_ENV
environment variable, which Sinatra checks when setting its environment.So to make sure you're running in the test environment, add this to the top of
spec_helper.rb
(or somewhere else at the start of your tests, but before you require Sinatra):You could then remove the
set :environment, :test
line as it's now redundant.This is similar to the other question you reference, but rack apps use
RACK_ENV
instead ofRAILS_ENV
.