From 6d95dfcc59a5096609b6c131b7b9ac69970ec49b Mon Sep 17 00:00:00 2001 From: Ana Rosas Date: Fri, 22 Apr 2016 13:20:49 -0500 Subject: [PATCH] Check if attribute to set is a Timestamp --- lib/simple_states/event.rb | 6 +++++- spec/events_spec.rb | 22 +++++++++++++++++++++- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/lib/simple_states/event.rb b/lib/simple_states/event.rb index a19f3cf..13a2f20 100644 --- a/lib/simple_states/event.rb +++ b/lib/simple_states/event.rb @@ -36,7 +36,11 @@ def set_attrs(obj, data) end def set_attr(obj, key, value) - obj.send(:"#{key}=", value) if obj.respond_to?(:"#{key}=") + obj.send(:"#{key}=", value) if obj.respond_to?(:"#{key}=") and not has_timestamp?(obj, key) + end + + def has_timestamp?(obj, key) + key.to_s.end_with?('_at') && obj.respond_to?(key) && obj.send(key) end def ordered?(obj, data) diff --git a/spec/events_spec.rb b/spec/events_spec.rb index 3109cc4..413a382 100644 --- a/spec/events_spec.rb +++ b/spec/events_spec.rb @@ -34,11 +34,31 @@ end describe 'when a timestamp is passed' do - let(:attrs) { { started_at: now - 60 } } + let(:attrs) { { started_at: now - 60, state: "started" } } it { expect { obj.start(attrs) }.to change { obj.started_at }.to(attrs[:started_at]) } end end + describe 'ignores timestamp' do + describe 'when started_at had been set earlier' do + let(:attrs) { { started_at: now - 60, finished_at: now - 50, state: "passed" } } + let(:early) { now - 55 } + before { obj.started_at = early } + before { obj.finish(attrs) } + it { expect(obj.started_at).to eq early } + it { expect(obj.finished_at).to eq attrs[:finished_at] } + end + + describe 'when finished_at had been set earlier' do + let(:attrs) { { started_at: now - 60, finished_at: now - 50, state: "passed" } } + let(:early) { now - 45 } + before { obj.finished_at = early } + before { obj.finish(attrs) } + it { expect(obj.started_at).to eq attrs[:started_at] } + it { expect(obj.finished_at).to eq early } + end + end + describe 'accepts an arbitrary attribute' do before { klass.send(:attr_accessor, :foo) } it { expect { obj.start(foo: :bar) }.to change { obj.foo }.to(:bar) }