Add an initial Track model implementation

This commit is contained in:
Petko Bordjukov 2014-08-10 20:30:37 +03:00
parent de9a3aea9d
commit 9f875a88bf
5 changed files with 51 additions and 0 deletions

View File

@ -6,6 +6,8 @@ class Conference < ActiveRecord::Base
validates :end_date, presence: true
validate :end_date_is_before_start_date
has_many :tracks
private
def end_date_is_before_start_date

10
app/models/track.rb Normal file
View File

@ -0,0 +1,10 @@
class Track < ActiveRecord::Base
belongs_to :conference
validates :name, presence: true
validates :color, presence: true, format: {with: /\A[a-f0-9]{6}\z/i}
def color=(hex_triplet)
write_attribute :color, hex_triplet.gsub(/\A#/,'') if hex_triplet
end
end

View File

@ -0,0 +1,11 @@
class CreateTracks < ActiveRecord::Migration
def change
create_table :tracks do |t|
t.string :name, null: false
t.string :color, null: false
t.references :conference, index: true
t.timestamps
end
end
end

9
spec/factories/tracks.rb Normal file
View File

@ -0,0 +1,9 @@
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :track do
name { |n| "Track#{n}" }
color '#000000'
conference
end
end

19
spec/models/track_spec.rb Normal file
View File

@ -0,0 +1,19 @@
require 'rails_helper'
RSpec.describe Track, :type => :model do
it 'is invalid without a name' do
expect(build(:track, name: '')).to have_error_on :name
end
describe 'color' do
it 'must be present' do
expect(build(:track, color: '')).to have_error_on :color
end
it 'must be a hex RGB triplet' do
expect(build(:track, color: 'foobar')).to have_error_on :color
expect(build(:track, color: '000000')).to_not have_error_on :color
expect(build(:track, color: '#000000')).to_not have_error_on :color
end
end
end