Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must I reload records in rspec after using customer validators?

I've got a model User 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 some 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 spec fails and the only way to make it pass is to reload the record in the spec:

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?

like image 603
railsuser400 Avatar asked Nov 17 '13 14:11

railsuser400


1 Answers

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

Secondly I would propose some changes to your code:

def create_options
  UserOptions.create(user: self)
end

should be

def create_options
  self.user_option.create
end

that way you don't have to reload an object after save, because the object already has the new UserOptions entity in it's relation.

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

like image 146
phoet Avatar answered Sep 28 '22 04:09

phoet