即使在控制器中调用了方法,模型也无法接收到来自方法的调用

Model failing to receive call from method even though the method is being called in the controller

我正在尝试编写测试以查看我的 Hospital 模型是否正在接收自定义方法 look_for_hospitals。

这是测试:

Rspec.describe HospitalsController, type: :controller do
    describe '#search' do
        it 'should call the model method to do the search' do
            # model should implement method look_for_hospitals
            expect(Hospital).to receive(:look_for_hospitals).with('keyword')
            # form in search page must be named 'keywords'
            get :search, params: {:keywords => 'keyword'}
            expect(assigns(:hospitals))
        end
    end

这是我的模型:

class Hospital<ApplicationRecord
    def self.look_for_hospitals term
    end
end

这里是 HospitalsController 中的方法搜索:

def search
    keyword = params[:keywords]
    @hospitals = Hospital.look_for_hospitals(keyword)
end

当我 运行 我的测试时,这是我遇到的错误:

  1) HospitalsController#search should call the model method to do the search
     Failure/Error: expect(Hospital).to receive(:look_for_hospitals).with('keyword')

       (Hospital(id: integer, cnes: string, number: integer, address: text, latitude: string, longitude: string, name: string, phones: text, nature: string, specialties: text, rpa: string, microregion: string, created_at: datetime, updated_at: datetime) (class)).look_for_hospitals("keyword")
           expected: 1 time with arguments: ("keyword")
           received: 0 times

我知道还没有实现任何东西,但我正在尝试先编写测试然后再编写方法的 tdd 方法。 对不起,如果我的英语有点奇怪,母语不是英语。

谢谢!

正如 Tom Lord 指出的那样,问题出在 Controller 开头的 before_action 行中。我只需要存根,问题就解决了。