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

David Chelimsky dchelimsky at gmail.com
Fri Jun 24 08:48:37 EDT 2011


On Jun 24, 2011, at 7:17 AM, John Feminella wrote:

> 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?

Just use before(:all). That's what it is designed for, and it tells you that you have stuff to clean up in an after(:all) hook.

HTH,
David


More information about the rspec-users mailing list