Sha256: 5a0814f39e9a2d1e60416347c5299585fc7c231d7b3dca1c64d328d6c880073a

Contents?: true

Size: 1.71 KB

Versions: 1

Compression:

Stored size: 1.71 KB

Contents

describe ActiveRecord::SafeInitialize do
  before(:all) { Post.create(title: "Test Post", body: "This is a test.", uuid: nil) }
  after(:all)  { Post.first.destroy }

  context "with: missing" do
    it "raises ArgumentError" do
      expect{ Post.safe_initialize(:uuid) }.to raise_error(ArgumentError)
    end
  end

  context "with: String" do
    it "uses the value as the default" do
      klass = Class.new(Post)
      klass.safe_initialize :uuid, with: 'foo'

      expect( klass.first.uuid ).to eq 'foo'
    end
  end

  context "with: Symbol" do
    it "sends the symbol to self to get value" do
      klass = Class.new(Post)
      klass.class_eval { def init_uuid; 'bar'; end }
      klass.safe_initialize :uuid, :with => :init_uuid

      expect( klass.first.uuid ).to eq 'bar'
    end
  end

  context "with: callable" do
    it "instance execs the callable to get the value" do
      klass = Class.new(Post)
      klass.class_eval { def init_uuid; 'baz'; end }
      klass.safe_initialize :uuid, with: ->{ self.init_uuid }

      expect( klass.first.uuid ).to eq 'baz'
    end
  end

  context "existing value" do
    let(:uuid) { SecureRandom.uuid }

    before(:each) { Post.first.update_attribute :uuid, uuid }

    it "does nothing" do
      klass = Class.new(Post)
      klass.safe_initialize :uuid, with: 'foo'

      expect( klass.first.uuid ).to eq uuid
    end
  end

  context "multiple attributes" do
    it "creates a default for each one" do
      klass = Class.new(Post)

      expect{ klass.safe_initialize :title, :body, :uuid, with: 'foo' }.to_not raise_error

      inst = klass.new
      expect( inst.title ).to eq 'foo'
      expect( inst.body ).to eq 'foo'
      expect( inst.uuid ).to eq 'foo'
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
activerecord-safe_initialize-0.1.0 spec/active_record/safe_initialize_spec.rb