阻止 Ruby on Rails 规范中的数据库回滚?
当使用 ActiveRecord 在 Ruby on Rails 2.3 中运行 RSpec 测试时,数据库会回滚到每个示例之后的 before :all
块(it
块)之后的状态。
然而,我想规范一个对象的生命周期,这意味着一一查看许多示例,更改状态并测试后置条件。对于回滚行为来说这是不可能的。
因此需要澄清一下:
describe MyModel
before :all { @thing = MyModel.create }
it "should be settable" do
lambda { @thing.a_number = 42 }.should_not raise_exception
end
it "should remember things" do
@thing.a_number.should == 42
# this fails because the database was rolled back ☹
end
end
是否有某种方法可以持久保存示例中所做的更改?
When running RSpec tests in Ruby on Rails 2.3 with ActiveRecord, the database gets rolled back to the state after a before :all
block after each example (it
block).
However, I want to spec the lifecycle of an object, which means going through a number of examples one by one, changing the state and testing postconditions. This is impossible with the rollback behaviour.
So to clarify:
describe MyModel
before :all { @thing = MyModel.create }
it "should be settable" do
lambda { @thing.a_number = 42 }.should_not raise_exception
end
it "should remember things" do
@thing.a_number.should == 42
# this fails because the database was rolled back ☹
end
end
Is there some way to persist changes made in examples?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我同意正常性,在这种情况下,看起来你最好使用包含两个断言的单个规范。
在某些情况下,关闭回滚很有帮助,例如,对于 Capybara 和 Selenium 进行更高级别的测试,在这种情况下,您可以使用
use_transactional_fixtures
配置选项。你可以把这个I agree with normalocity, in this case it looks like you would be better off with a single spec containing two assertions.
There are cases in which it is helpful to turn off rollbacks, e.g. for higher level tests with Capybara and Selenium, in which case you can use the
use_transactional_fixtures
configuration option. You can put thi嗯,这取决于你想做什么。如果您正在测试生命周期(随着时间的推移发生的一系列事情),那么这更多的是集成测试的领域,您可以在 Cucumber 等工具中构建更多集成测试。Spec 更适合进行小型测试代码位。
从技术上讲,您可以简单地编写一个包含多个
.should
语句的长规范测试,只要所有这些都通过,那么您就已经有效地获得了您所描述的测试类型。然而,根据我的经验,这并不是真正的规范旨在为您提供的功能。我想我想说的是,不要试图阻止回滚 - 这不是它要做的事情。要么使用更适合您想要构建的测试类型的工具,要么编写一个包含多个
.should
语句的较长测试。Well, that depends on what you're trying to do. If you're testing the life cycle (a series of things that happen over time), that's more the realm of integration tests, which you can build more in tools such as Cucumber, etc. Spec is more designed to do small tests of small bits of code.
It's technically possible for you to simply write a long spec test, with multiple
.should
statements, and so long as all of them pass, then you've effectively got the kind of test you're describing. However, that's not really, in my experience, what spec is designed to give you.I guess what I'm saying is, don't try to prevent the rollback - that's not what it's there to do. Either use a tool more designed to do the kinds of tests you're looking to build, or write a longer test that has multiple
.should
statements.