Reputation: 1123
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
Upvotes: 1
Views: 1785
Reputation: 6072
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.
Upvotes: 2