开发者

Prevent database rollback in specs in Ruby on Rails?

开发者 https://www.devze.com 2023-04-04 15:48 出处:网络
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).

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_exceptio开发者_运维百科n
  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?


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

RSpec.configure do |config|
  config.use_transactional_fixtures = false
end


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消