I have a spec testing a model that looks like this:
RSpec.describe SomeModel, type: :model do
subject { described_class.new(test_amount: 99) }
describe 'validates a column' do
it 'does some validations' do
expect(subject).to validate_presence_of(:test_amount)
end
end
end
And a model that looks like this:
class SomeModel < ApplicationRecord
validates :test_amount, presence: true
end
And in the schema it's column looks like this with a not-null set:
t.integer "test_amount", default: 0, null: false
No matter what I do or where I put the code, test_amount is always nil when being tests and errors. I've tried moving the test lines around, putting the subject in a before etc, but always the database is throwing a non-null error and even if I raise in the model code the test_amount value is not 99 it is nil. If I raise the test value in a before like this:
before do
raise subject.test_amount
end
That does result in a 99, however if I remove this, it is always nil and throws an error when it gets to the expect part of the test.
What am I missing in order to get this test to work, I just cannot seem to get the test_amount
to set to 99 when being tested in the actual test step.
The test always throws the error:
PG::NotNullViolation: ERROR: null value in column "test_amount" of relation "some_models" violates not-null constraint
or similar, I have but in before-validations to check the value of test_amount
and it does not get set.
Thanks for you help, I feel like there's something really basic I'm missing here.
First of all, verify that -
Moreover, try moving this line inside the describe
block -
subject { described_class.new(test_amount: 99) }