2017-03-25 5 views
0

私はこの単純なコードRSpecがなぜ前に(:それぞれ)実行されなかったのですか?

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 

を持っており、このスペック(まだ仕事をしながら、私はできる限り小さく)

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が印刷されることは決してありませんし、binding.pryを実行し、テストを停止しません。メッセージで失敗するNo such file or directory @ rb_sysopen - /test/data.json

これはすべて(before :(each)が実行されないことを意味します。

なぜですか?
修正方法?

+0

相対パスは使用していますか? '。/ test/data.json' –

答えて

1

最初のbeforeブロックで失敗するため、目的のメッセージは印刷されません。 Rspec doc about execution order

あなたは絶対パスを提供するので、それは失敗するので、それは/test/data.json

をチェックしているいずれかのテスト、すなわちへの相対パスを使用します。 ../data.json(ちょうど推測)、 またはフルパス。 レールの場合: Rails.root.join('path_to_folder_with_data_json', 'data.json')

関連する問題