Skip to content

Instantly share code, notes, and snippets.

@ClayShentrup
Last active April 22, 2017 17:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ClayShentrup/82dfa937ad9490b7433aeb24100ee099 to your computer and use it in GitHub Desktop.
Save ClayShentrup/82dfa937ad9490b7433aeb24100ee099 to your computer and use it in GitHub Desktop.
Skipping ActiveRecord association validations in tests
class Car < ActiveRecord::Base
attr_accessor(:skip_association_presence_validations)
validates(:driver, presence: true, unless: :skip_association_presence_validations)
# creates driver_license_number method
delegate(:license_number, to: :driver, prefix: true)
end
RSpec.describe(Car) do
describe('validations') do
# Examples of specs that can be run without associations being validated
it { is_expected.to validate_presence_of(:make) }
it { is_expected.to validate_presence_of(:model) }
# We enable association presence validations selectively
describe('on associations') do
before { subject.skip_association_presence_validations = false }
it { is_expected.to validate_presence_of(:patient) }
end
end
end
FactoryGirl.define do
factory(:cars) do
skip_association_presence_validations
end
end
FactoryGirl.define do
trait(:skip_association_presence_validations) do
callback(:after_stub, :after_build) do |model|
model.skip_association_presence_validations = true
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment