Question

I want to use an around hook to run my specs with a temporary directory present and have the temporary directory cleaned up afterward.

describe FileManipulatingClass do

  around(:each) do |example|
    Dir.mktmpdir do |dir|
      example.run
    end
  end

  subject { described_class.new dir }

  context "given its help file exists" do
    let(:file_path) { File.join dir "help.txt"}
    before(:each) do
      File.open(file_path, 'w') {|io| io.write "some data" }
    end

    its(:help_text) { should eq("some data") }

  end

end

This won't work because the "dir" isn't set for the context. How can I do the equivalent of

let(:dir) { ... }

and provide a value that only becomes available in the around hook?

Was it helpful?

Solution

One way would be to set an instance variable within your around hook, as follows:

describe FileManipulatingClass do

  around(:each) do |example|
    Dir.mktmpdir do |dir|
      @dir = dir
      example.run
    end
  end

  subject { described_class.new @dir }

  context "given its help file exists" do
    let(:file_path) { File.join @dir "help.txt"}
    before(:each) do
      File.open(file_path, 'w') {|io| io.write "some data" }
    end

    its(:help_text) { should eq("some data") }

  end

end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top