Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

Rails tests skipping custom validations or custom validation not working?

I have a model Subscription with a boolean attribute :fee which should not be modified after the creation of a Subscription.

I added a custom validation like this:

validate :fee_not_changed

def fee_not_changed
  return unless created_at != updated_at && fee_changed?

  errors.add :fee, :changed, message: "cannot be changed"
end

Our API is not allowing us to update :fee (the error is returned) but I can update the attribute in tests despite the custom validation like so:

test "fee cant be edited after creation" do
  subscription = subscriptions(:with_fee)
  subscription.update!(fee: false)

  assert_not subscription.saved_change_to_fee?
end

Expected true to be nil or false

Also, if I put a byebug before the assertion, I can see that it effectively updates the attribute skipping the custom validation.

What's the problem? Thanks for any help provided.

question from:https://stackoverflow.com/questions/66049180/rails-tests-skipping-custom-validations-or-custom-validation-not-working

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I believe this is a caching issue.

Can you try reloading the subscription with .reload?

assert_not subscription.reload.saved_change_to_fee?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...