Permalink
Browse files

Extract validations to model

  • Loading branch information...
1 parent 908a981 commit 61ad0ec5a2f273bcdc083868e37ffea6d9ad301d @sevos committed Jan 21, 2012
View
13 lib/timebacus/models/activity.rb
@@ -1,9 +1,22 @@
module Timebacus
class Activity
attr_accessor :id, :duration, :description
+ attr_accessor :errors
def initialize(duration, description)
@duration, @description = duration, description
end
+
+ def valid?
+ validate
+ self.errors.empty?
+ end
+
+ private
+ def validate
+ self.errors = []
+ self.errors << 'description' if !@description || @description == '' # non blank
+ self.errors << 'duration' if @duration.to_i.abs != @duration # positive integer
+ end
end
end
View
16 lib/timebacus/use_cases/report_activity.rb
@@ -6,17 +6,13 @@ def initialize(duration, description)
end
def execute
- validate
- ActivityRepository.store(Activity.new(@duration, @description)).id
- end
-
- private
- def validate
- errors = []
- errors << 'description' if !@description || @description == '' # non blank
- errors << 'duration' if @duration.to_i.abs != @duration # positive integer
- raise ArgumentError, errors.join(', ') unless errors.empty?
+ activity = Activity.new(@duration, @description)
+ if activity.valid?
+ ActivityRepository.store(activity).id
+ else
+ raise ArgumentError, activity.errors.join(', ')
end
+ end
end
end
View
17 spec/use_cases/report_activity_spec.rb
@@ -3,7 +3,6 @@
require 'timebacus/use_cases/report_activity'
describe Timebacus::ReportActivity do
- let(:activity) { mock(id: 5, duration: 1800, description: 'remote work') }
mock_const Timebacus::ReportActivity, 'Activity' do |activity_class|
activity_class.stub(new: activity)
end
@@ -12,6 +11,8 @@
end
context 'with valid data' do
+ let(:activity) { mock(id: 5, duration: 1800, description: 'remote work',
+ valid?: true) }
subject { Timebacus::ReportActivity.new 1800, 'remote work' }
it 'returns id of new activity' do
@@ -25,19 +26,13 @@
end
end
- context 'with description missing' do
- subject { Timebacus::ReportActivity.new 1800, '' }
-
- it 'raises ArgumentError' do
- -> {subject.execute }.should raise_error(ArgumentError, 'description')
- end
- end
-
- context 'with negative duration' do
+ context 'with invalid data' do
+ let(:activity) { mock(valid?: false, errors: ['duration', 'description']) }
subject { Timebacus::ReportActivity.new -1800, 'creating bugs' }
it 'raises ArgumentError' do
- -> {subject.execute }.should raise_error(ArgumentError, 'duration')
+ -> {subject.execute }.
+ should raise_error(ArgumentError, 'duration, description')
end
end
end

0 comments on commit 61ad0ec

Please sign in to comment.