-
-
Notifications
You must be signed in to change notification settings - Fork 911
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Should belong_to with 'optional' not working #1153
Comments
For reference, looks like this is the PR that added that: #1058 |
@jasonperrone @derekcannon Do you have anything else in your Event model, such as a presence validation, that could be overriding the behavior of |
@mcmire I was just referencing the PR. I am not currently on 4.0.0 RC-1, and I haven't personally experienced this problem. |
I recently hit this exact same issue and have done some digging - we had a number of models that had optional associations and the tests were passing so the feature does appear to work just fine but it was just on a single model that it was failing. I isolated the issue down to some additional validation rules which appear to be conflicting with the require checking so at a guess it is just checking for the presence of the association in the validation errors. The scenario where we were hitting the error was on a class User < ApplicationRecord
...
belongs_to :company, optional: true
validates_presence_of :company, unless: :is_superadmin
validate :absence_of_company, if: :is_superadmin
...
def absence_of_company
errors.add(:company_id, 'must be blank for superadmin users') if company_id.present?
end
end I would assume then that when the test runs, because the |
Hey @pareeohnos, thanks for the example. That makes perfect sense. I need to think about this further, but just as a quick sketch, I wonder if, for these kinds of scenarios, it would be better to have an additional qualifier to
This way, the matcher wouldn't even bother checking any kind of presence validation, and this would allow you to test presence or absence manually without the matcher interfering. |
Ah that would work - I assume that the |
I just merged in a commit that adds a |
|
Sorry, I've updated the comment now :) |
Many thanks @pareeohnos and @mcmire. You helped me. |
4.0.0.rc1
Model Event has this:
belongs_to :event_category, optional: true
Test has this:
should belong_to(:event_category).optional
Get this:
Expected Event to have a belongs_to association called event_category (the association should have been defined with
optional: true
, but was not)The text was updated successfully, but these errors were encountered: