[rspec-users] Is there a way to run `let` once per context?

John Feminella johnf at bitsbuilder.com
Fri Jun 24 08:17:21 EDT 2011


hello,

I have a monolithic test that looks like this:

======
describe Model do
  describe "#method" do
    let!(:expensive) { ... }

    it "should do a lot of things" do
      expensive.should be_foo
      expensive.should be_bar
      expensive.should be_baz
    end
  end
end
======

I would like to refactor the large spec into smaller ones:

======
    it "should be foo" { expensive.should be_foo }
    it "should be bar" { expensive.should be_bar }
    it "should be baz" { expensive.should be_baz }
======

However, doing this slows down the tests a bit, because the
`expensive` method requires hitting the database.

Suppose that I can guarantee that none of the tests or the methods
they call will be modifying the object returned by the `expensive`
method. Is there a way to tell RSpec to memoize the `expensive` result
across the context, and not just across an individual test run?

Alternatively, should I just use before(:all) for this?
--
John Feminella
Principal Consultant, BitsBuilder
LI: http://www.linkedin.com/in/johnxf
SO: http://stackoverflow.com/users/75170/


More information about the rspec-users mailing list