1

In my user model I have a function that generates an account ID for the user. I would like to write a test that creates a user (I'm using FactoryGirl) then checks to ensure the account_id field isn't empty after the user is saved. With my current test I'm getting an error that says the following:

NoMethodError: undefined method `to_not=' for #<RSpec>

user.rb

class User < ActiveRecord::Base
  before_create :generate_account_id

  private

    def generate_account_id
      self.account_id = loop do
        random_account_id = rand.to_s[2..6]
        break random_account_id unless self.class.exists?(account_id: random_account_id)
      end
    end
end

user_spec.rb

#spec/models/user_spec.rb
require 'spec_helper'
require 'rails_helper'

describe User do
  it "has a valid factory" do
    user = create(:user, :user)
    expect(user).to be_valid
  end

  it "receives a Account ID on successful create" do
    user = FactoryGirl.build(:user)
    expect(user.account_id).to_not == nil
  end
end

1 Answer 1

2

Your error is due to a typo: "undefined method" means you're calling something that doesn't exist. In this case, Ruby's interpreting your .to_not == call as an attempt at assignment. If you check the RSpec documentation for ==, you'll find it uses the be method as well:

expect(user.account_id).to_not be == nil

Alternatively, your test might be clearer if you use the be_nil matcher instead:

expect(user.account_id).to_not be_nil

The other aspect of this problem is you're using build, not create. FactoryGirl's build method (see section "Using factories"), much like ActiveRecord's, doesn't save the object. As a result, the before_create callback won't fire.

Sign up to request clarification or add additional context in comments.

3 Comments

That type fixed things in terms of syntax. However, I'm thinking my code isn't the proper way to test callbacks. I received the following Failure/Error: expect(user.account_id).to_not be_nil expected: not nil got: nil It seems like the callback isn't being called with my test block.
That's a bug in your code. :) FactoryGirl's build method (see section "Using factories"), much like ActiveRecord's, doesn't save the object. As a result, the before_create callback won't fire.
You're right :). I changed it from build to create and the test is passing now. Do you want to add that change to your answer so I can accept? Thanks for the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.