Why should I reload records in rspec after using client validators?

I have a User model that has options created in a callback after it is created.

 # User has_one :user_options after_create :create_options private def create_options UserOptions.create(user: self) end 

I have a simple rspec coverage for this:

 describe "new user" do it "creates user_options after the user is created" do user = create(:user) user.user_options.should be_kind_of(UserOptions) end end 

Everything worked until I added custom validation to the user model.

 validate :check_whatever, if: :blah_blah 

Now the specification fails, and the only way to do this is to reload the record in the specification:

 it "creates user_preferences for the user" do user = create(:user) user.reload user.user_options.should be_kind_of(UserOptions) end 

What is the reason for this?

+6
source share
1 answer

First of all, I would recommend reading this article about rail debugging applications: http://nofail.de/2013/10/debugging-rails-applications-in-development/

Secondly, I would suggest some changes to your code:

 def create_options UserOptions.create(user: self) end 

it should be

 def create_options self.user_option.create end 

this way you do not need to reload the object after saving, because the object already has a new UserOptions object in it.

Assuming you are using fixtures from the create(:user) code. There may be a problem with the data that you use in user.yml and the confirmation that you wrote, but unfortunately did not publish here.

+1
source

Source: https://habr.com/ru/post/958260/


All Articles