简体   繁体   中英

How can I make my specs run faster?

I have several spec files that look like the following:

describe "My DSL" do

  before :each do
    @object = prepare_my_object
  end

  describe "foo" do

    before :each do
      @result = @object.read_my_dsl_and_store_stuff_in_database__this_is_expensive
    end

    it "should do this" do
      @result.should be_this
    end

    it "should not do that" do
      @result.should_not be_that
    end

    # ... several more tests about the state of @result
  end

  # ...
end

These tests take a long time, essentially because the second before :each block runs every time. Using before :all instead does not really help, because it gets called before the outer before :each . Putting all expectations in one single it block would help, but this is considered bad style.

What is best practice to have my expensive method being executed only once?

The fastest way to speed up rspec is to completely decouple the database. The DSL problem is a different problem from the get stuff in to and out of a db problem. If you have one method doing both, is it is possible to break the method into pieces?

Ideally, your DSL would be cached locally, so it wouldn't have to be pulled from the db on every request anyway. It could get loaded once in memory and held there before refreshing.

If you run against a local, in-memory cache, and decouple the db, does that speed things up? If yes, then it's the db call that's slow. If your DSL is completely loaded up in memory and the tests are still slow, then the problem is your DSL itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM