![](/img/trans.png)
[英]Ruby on Rails Rspec NoMethodError: undefined method 'not_to'
[英]Rails - RSpec NoMethodError: undefined method
我正在嘗試測試一種非常簡單的方法,該方法接受2個數字並使用它們得出一個百分比。 但是,當我嘗試運行測試時,它失敗並顯示以下錯誤:
NoMethodError: undefined method `pct' for Scorable:Module
./spec/models/concerns/scorable_spec.rb:328:in `block (2 levels) in
<top (required)>'
./spec/rails_helper.rb:97:in `block (3 levels) in <top (required)>'
./spec/rails_helper.rb:96:in `block (2 levels) in <top (required)>'
-e:1:in `<main>'
這是我的模塊規格文件:
require 'rails_helper'
RSpec.describe Scorable, :type => :concern do
it "pct should return 0 if den is 0 or nil" do
expect(Scorable.pct(nil, 15)).to eq(0)
expect(Scorable.pct(0, 15)).to eq(0)
end
end
這是位於Scorable.rb中的pct方法:
def pct(num,den)
return 0 if num == 0 or num.nil?
return (100.0 * num / den).round
end
這是我的rspec_helper:
if ENV['ENABLE_COVERAGE']
require 'simplecov'
SimpleCov.start do
add_filter "/spec/"
add_filter "/config/"
add_filter '/vendor/'
add_group 'Controllers', 'app/controllers'
add_group 'Models', 'app/models'
add_group 'Helpers', 'app/helpers'
add_group 'Mailers', 'app/mailers'
add_group 'Views', 'app/views'
end
end
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions =
true
end
config.raise_errors_for_deprecations!
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
end
我是RSpec的新手,並且已經為這個問題困擾了一天多。 它肯定指向現有方法,因為當我在RubyMine中使用“轉到聲明”時,它將打開方法聲明。 誰能給我一些啟示? 我敢肯定,我忽略了一個非常簡單的事情。
為了使模塊方法可通過Module.method
調用,應在模塊范圍內聲明符號。
module Scorable
def self.pct(num,den)
return 0 if num == 0 or num.nil?
return (100.0 * num / den).round
end
end
要么:
module Scorable
class << self
def pct(num,den)
return 0 if num == 0 or num.nil?
return (100.0 * num / den).round
end
end
end
module Scorable
module_function
def pct(num,den)
return 0 if num == 0 or num.nil?
return (100.0 * num / den).round
end
end
請注意,后者在該模塊中聲明了模塊方法和常規實例方法。
旁注:在方法的最后一行中使用return
被認為是代碼異味,應避免:
module Scorable
def self.pct(num,den)
return 0 if num == 0 or num.nil?
(100.0 * num / den).round
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.