Last active
April 22, 2017 17:45
-
-
Save ClayShentrup/82dfa937ad9490b7433aeb24100ee099 to your computer and use it in GitHub Desktop.
Skipping ActiveRecord association validations in tests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
FactoryGirl.define do | |
factory(:cars) do | |
skip_association_presence_validations | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment