Last active
February 17, 2017 19:37
-
-
Save Incanus3/24f87857504021642d312e189a3fdfcc to your computer and use it in GitHub Desktop.
dry-types inconsistent behavior with default & constructor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "bundler/inline" | |
gemfile(true) do | |
source "https://rubygems.org" | |
gem 'dry-types', github: "dry-rb/dry-types", branch: 'master' | |
gem 'dry-struct', github: "dry-rb/dry-struct", branch: 'master' | |
gem 'rspec' | |
gem 'timecop' | |
end | |
require 'dry-types' | |
require 'dry-struct' | |
require 'rspec/autorun' | |
require 'timecop' | |
module Types | |
include Dry::Types.module | |
end | |
describe 'dry-types' do | |
let(:time) { Time.iso8601('2001-02-03T04:05:06.123+00:00') } | |
context 'value provided' do | |
it 'runs it through constructor' do | |
expect(Types::Form::Time | |
.constructor { |t| t.round } | |
.default { Time.now }[time]).to eq time.round | |
end | |
end | |
context 'nil provided' do | |
it 'ignores constructor' do | |
pending 'broken' | |
expect(Types::Form::Time | |
.constructor { |t| t.round } | |
.default { time }[nil]).to eq time.round | |
end | |
end | |
end | |
class Model < Dry::Struct | |
constructor_type :schema | |
attribute :attr, Types::Form::Time | |
.constructor { |t| t.round } | |
.default { Time.now } | |
end | |
describe 'default + constructor combination' do | |
before do | |
Timecop.freeze | |
end | |
after do | |
Timecop.return | |
end | |
let(:time) { Time.iso8601('2001-02-03T04:05:06.123+00:00') } | |
context 'value provided' do | |
it 'runs it through constructor' do | |
model = Model.new(attr: time) | |
expect(model.attr).not_to eq time | |
expect(model.attr).to eq time.round | |
end | |
end | |
context 'value not provided' do | |
it 'uses default and runs it through constructor' do | |
model = Model.new() | |
expect(model.attr).to eq Time.now.round | |
end | |
end | |
# it could be OK not to run defaults through constructor, but it doesn't seem right to run them | |
# through in one case and not in the other | |
context 'nil provided' do | |
it 'uses default, but does NOT run it through constructor' do | |
pending 'broken' | |
model = Model.new(attr: nil) | |
expect(model.attr).to eq Time.now.round | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment