简体   繁体   English

rspec测试在Rails控制器中失败

[英]rspec test fails code in rails controller

In my application_controller.rb, i have a line of code as follows: 在我的application_controller.rb中,我有一行代码如下:

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 在我的rspec代码中,我有一行代码可以访问application_controller的索引路径,如下所示

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 当我直接运行代码时,它可以正常运行,但是当它通过rspec访问application_controller.rb时,出现错误提示

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 我不确定是否通过rspec和capybara收到此错误,但是如果我将代码运行为

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

It executes perfectly with no errors. 它执行完美,没有错误。 Kinda confused what the uniq! Kinda弄糊涂了什么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! 我不认为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). 如果未进行任何更改(即未找到任何重复项),则返回nil。 https://ruby-doc.org/core-2.2.0/Array.html#method-i-uniq-21 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: 另一方面, uniq工作方式如下:

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. uniq的输出上,可以安全地运行compact来删除nil值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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