MotionDataWrapper を使ったモデルのスペックを書く

CoreData を使ったモデルのスペックを書く場合、NSManagedObjectContext などのセットアップと、 テストデータの後始末が面倒。

このうちセットアップは MotionDataWrapper が楽にしてくれる。 あとは後始末だけど、こいつも MotionDataWrapper の spec においてあるヘルパーを使えば良さそう。

# coding: utf-8

module MotionDataWrapper
  module Delegate
    def clean_data
      @managedObjectContext = nil
      @managedObjectModel = nil
      @coordinator = nil
      @sqlite_path = nil
      manager = NSFileManager.defaultManager
      manager.removeItemAtURL sqlite_url, error:nil if manager.fileExistsAtPath sqlite_url.path
    end
  end
end

module MotionDataWrapper
  class Model
    module CoreData

      module ClassMethods

        def clean_entity_description
          @_metadata = nil
        end

      end

    end
  end
end

def clean_core_data
  App.delegate.clean_data
  Task.clean_entity_description
end

こんな感じでスペックを書ける。

# coding: utf-8

describe "Task" do
  before do
    @delegate = App.delegate
  end

  after do
    clean_core_data
  end

  describe "#completed=" do
    it "should complete task" do
      task = Task.create(title:"foo")
      task.completed = true
      task.completed.should == 1
      task.save.should == true

      task = Task.first
      task.completed.should == 1
    end
  end
end

CoreData を使ったモデルのスペックを書く敷居がだいぶ下がったと思う。