简体   繁体   中英

rspec test fails code in rails controller

In my application_controller.rb, i have a line of code as follows:

def index
 CaseStatus.order(:application_source).pluck(:application_source).uniq!
end

In my rspec code, i have a line of code that visits the index path of application_controller as follows

visit applications_path

When i run the code directly, it works perfectly but when it visits application_controller.rb via rspec, i get an error which says

NoMethodError:
  undefined method `compact' for nil:NilClass

Not sure while i get this error via rspec and capybara but if i run the code as

def index
 CaseStatus.order(:application_source).pluck(:application_source)
end

It executes perfectly with no errors. Kinda confused what the uniq! breaks in the code that suddenly the result becomes nil.

i get this error

 Failure/Error: @application_channels = CaseStatus.order(:application_source).pluck(:application_source).uniq!.compact if CaseStatus.order(:application_source).present?

 NoMethodError:
   undefined method `compact' for nil:NilClass
 # ./app/controllers/loan_applications_controller.rb:53:in `index'

I do not think uniq! is the method you would like to use in this case, see:

Returns nil if no changes are made (that is, no duplicates are found). https://ruby-doc.org/core-2.2.0/Array.html#method-i-uniq-21

So it works like this:

2.3.1 :008 > a = [1,2,3,3,nil].uniq!
 => [1, 2, 3, nil]
2.3.1 :009 > a = [1,2,3,nil].uniq!
 => nil
2.3.1 :010 >

on the other hand uniq works like:

2.3.1 :010 > a = [1,2,3,3,nil].uniq
 => [1, 2, 3, nil]
2.3.1 :011 > a = [1,2,3,nil].uniq
 => [1, 2, 3, nil]

and on the output of uniq it is safe to run compact to remove nil values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM