Marko Avlijaš
Marko Avlijaš

Reputation: 1649

RSpec why is before(:each) never executed?

I have this simple code

require 'json'

module Html
  class JsonHelper
    attr_accessor :path

    def initialize(path)
      @path = path
    end

    def add(data)
      old = JSON.parse(File.read(path))
      merged = old.merge(data)
      File.write(path, merged.to_json)
    end
  end
end

and this spec (reduced as much as I could while still working)

require 'html/helpers/json_helper'

describe Html::JsonHelper do
  let(:path) { "/test/data.json" }
  subject { described_class.new(path) }

  describe "#add(data)" do
    before(:each) do
      allow(File).to receive(:write).with(path, anything) do |path, data|
        @saved_string = data
        @saved_json = JSON.parse(data)
      end

      subject.add(new_data)
    end

    let(:new_data) { { oldestIndex: 100 } }
    let(:old_data) { {"test" => 'testing', "old" => 50} }

    def stub_old_json
      allow(File).to receive(:read).with(path).and_return(@data_before.to_json)
    end

    context "when given data is not present" do
      before(:each) do
        puts "HERE"
        binding.pry
        @data_before = old_data
        stub_old_json
      end

      it "adds data" do
        expect(@saved_json).to include("oldestIndex" => 100)
      end

      it "doesn't change old data" do
        expect(@saved_json).to include(old_data)
      end
    end
  end
end

HERE never gets printed and binding.pry doesn't stop execution and tests fail with message No such file or directory @ rb_sysopen - /test/data.json

This all means that before(:each) never gets executed.

Why?
How to fix it?

Upvotes: 0

Views: 250

Answers (1)

LucasM
LucasM

Reputation: 373

It does not print desired message because it fails at the first before block. Rspec doc about execution order

It fails because you provided an absolute path, so it is checking /test/data.json

Either use relative path to the test ie. ../data.json (just guessing), or full path. In case of rails: Rails.root.join('path_to_folder_with_data_json', 'data.json')

Upvotes: 1

Related Questions