我遇到了一个奇怪的错误:
班级:
module AnimalSanctuary
module AnimalInspector
class AnimalPicker
def initialize(number_of_animals, ids)
@number_of_animals = number_of_animals
@ids = ids
end
...
def pick_animals(animal)
end
end
end
测试:
require 'rails_helper'
RSpec.describe AnimalSanctuary::AnimalInspector::AnimalPicker do
describe ".pick_animals" do
context "pick an available animal" do
it "returns animal name" do
expect(AnimalSanctuary::AnimalInspector::AnimalPicker.pick_animals("Dog")).to eq("Dog")
end
end
end
end
我收到以下错误:
NoMethodError:
undefined method `pick_animals' for AnimalSanctuary::AnimalInspector::AnimalPicker:Class
Rspec调用该类,但不调用困扰我的方法。我在做错什么吗?
答案 0 :(得分:1)
pick_animals
的定义是实例方法。
要调用它,您将需要使用new
方法实例化该类的对象,如下所示。我已经将随机值传递给您的初始值设定项(1,[1,2]),但是您可以根据需要设置它们:
number_of_animals = 1
ids = [1,2]
AnimalSanctuary::AnimalInspector::AnimalPicker.new(number_of_animals, ids).pick_animals("Dog")
否则,要按其调用方式进行调用,则需要使用self.pick_animals
将其重新定义为类方法,如下所示:
module AnimalSanctuary
module AnimalInspector
class AnimalPicker
...
def self.pick_animals(animal)
end
end
end
答案 1 :(得分:0)
是的pick_animals
是一个实例方法。
您可以在rspec中使用以下内容
expect_any_instance_of(nimalSanctuary::AnimalInspector::AnimalPicker).to receive(:pick_animals).with("dogs").to_eq("Dog")
希望这会有所帮助