Skip to content

Instantly share code, notes, and snippets.

@christianrolle
Last active May 3, 2020 23:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save christianrolle/0aa4a2bc96ee8bd22227 to your computer and use it in GitHub Desktop.
Save christianrolle/0aa4a2bc96ee8bd22227 to your computer and use it in GitHub Desktop.
require 'active_record'
require 'jc-validates_timeliness'
require 'shoulda/matchers'
Dir[File.dirname(__FILE__) + "/support/**/*.rb"].each {|f| require f}
connection_info = YAML.load_file("config/database.yml")["test"]
ActiveRecord::Base.establish_connection(connection_info)
RSpec.configure do |config|
config.around do |example|
ActiveRecord::Base.transaction do
example.run
raise ActiveRecord::Rollback
end
end
end
class Stopwatch < ActiveRecord::Base
attr_accessible :label, :premedication_configuration_id, :starts_automatically
belongs_to :premedication_configuration
has_many :premedication_stopwatches
before_create :set_default_label
before_destroy proc { return false }, if: :mandatory?
validates :label, presence: true, on: :update
validates :label, length: { maximum: 30 }
validates :premedication_configuration, presence: true
delegate :future?, to: :premedication_configuration
scope :named, -> (term) { where(name: term) }
def to_s
label
end
def mandatory?
name.present?
end
private
def set_default_label
self.label ||= I18n.t('new_stopwatch')
end
end
require 'active_record_spec_helper'
require 'models/stopwatch'
require 'models/premedication_configuration'
describe Stopwatch do
# the stopwatch setup is odd, because I want to mock the associated premedication_configuration
let(:stopwatch) {
stopwatch = Stopwatch.new(label: 'Test')
# stopwatch.premedication_configuration = mock_model(PremedicationConfiguration)
# --> mock_model fails with:
# Failure/Error: stopwatch.premedication_configuration = mock_model(PremedicationConfiguration)
# NoMethodError:
# undefined method `mock_model' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1:0x00000002be82d0>
stopwatch.premedication_configuration = PremedicationConfiguration.new
stopwatch
}
subject { stopwatch }
describe "accessible attributes" do
it { expect(subject).to allow_mass_assignment_of(:label) }
it { expect(subject).to allow_mass_assignment_of(:premedication_configuration_id) }
it { expect(subject).to allow_mass_assignment_of(:starts_automatically) }
it { expect(subject).not_to allow_mass_assignment_of(:name) }
end
describe "validations" do
it { expect(subject).to be_valid }
it { expect(subject).to validate_presence_of(:label).on(:update) }
it { expect(subject).to ensure_length_of(:label).is_at_most(30) }
it { expect(subject).to validate_presence_of(:premedication_configuration) }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment