user938363
user938363

Reputation: 10378

NoMethodError for object

Here is the code

  #add email of team lead of the current user
  def add_the_tl_email(to_address, session_user_id)
    ul = UserLevel.find_by_user_id(session_user_id)
    if !ul.team.nil? && !ul.role.nil?
      User.user_status('active').joins(:user_levels).where(:user_levels => {:position => 'tl', 
                                                      :role => ul.role, 
                                                      :team => ul.team }).each do
        |u| to_address << u.email 
      end
    end
  end

The error from spec:

  1) CustomersController GET customer page 'create' successful should create one customer record
     Failure/Error: post 'create', :customer => @customer
     NoMethodError:
       undefined method `team' for nil:NilClass
     # ./app/mailers/user_mailer.rb:36:in `add_the_tl_email'
     # ./app/mailers/user_mailer.rb:15:in `notify_tl_dh_ch_ceo'
     # ./app/controllers/customers_controller.rb:27:in `create'
     # ./spec/controllers/customers_controller_spec.rb:48:in `block (5 levels) in <top (required)>'
     # ./spec/controllers/customers_controller_spec.rb:47:in `block (4 levels) in <top (required)>'

team is a field in user_level. Here is the user_level in factory:

Factory.define :user_level do |level|

  level.role                 "sales"
  level.position             "member"
  level.team                 1
  level.association          :user
end

In rails console, the ul.team.nil? returns either true or false on test data generated by factory.

Since team is a field in user_level, why there is error in spec like: NoMethodError: undefined method `team' for nil:NilClass ?

Thanks.

Upvotes: 0

Views: 321

Answers (2)

user166390
user166390

Reputation:

The issues is that nil.team is not a method*

NoMethodError:
   undefined method `team' for nil:NilClass

That is, ul evaluates to nil: check ul.nil? before checking ul.team.nil?... but might want to find out why the find failing to start with ;-)

Happy coding.


*This is what the real error message says, the title of the post is garbage :-/

Upvotes: 3

Ray Toal
Ray Toal

Reputation: 88488

The call in

 ul = UserLevel.find_by_user_id(session_user_id)

returned nil and thus nil was assigned to ul.

So when you called

!ul.team.nil?

Ruby tried to call team on nil. nil is an instance of NilClass and there is no method named team on NilClass.

Upvotes: 2

Related Questions