【问题标题】:How to stub Searchkick in search method in controller如何在控制器的搜索方法中存根 Searchkick
【发布时间】:2016-03-12 09:16:23
【问题描述】:

我是 RSpec 的新手。我想测试我的搜索控制器。我尝试在控制器中存根我的搜索方法,但它总是失败。

 Failure/Error: expect(Doctor).to receive(:search).with(search_param)
   (<Doctor(id: integer, name: string, address: string, phone: string, is_active: boolean, field_id: integer, created_at: datetime, updated_at: datetime, email: string, encrypted_password: string, reset_password_token: string, reset_password_sent_at: datetime, remember_created_at: datetime, sign_in_count: integer, current_sign_in_at: datetime, last_sign_in_at: datetime, current_sign_in_ip: inet, last_sign_in_ip: inet, roles: integer, description: text, avatar_file_name: string, avatar_content_type: string, avatar_file_size: integer, avatar_updated_at: datetime, avatar_processing: boolean, title: string, valid_doctor: boolean, verification_photo_file_name: string, verification_photo_content_type: string, verification_photo_file_size: integer, verification_photo_updated_at: datetime) (class)>).search("rizky")
       expected: 1 time with arguments: ("rizky")
       received: 0 times

隔离 Searchkick 的正确方法是什么?

这是我在控制器中的搜索方法:

def search
    @doctors = []
    keyword = params[:keyword]
    @doctors = call_search_in_doctor(keyword) if keyword.present?
    respond_to do |format|
      format.json { render json: @doctors, status: 200 }
      format.html { render 'users/search/index.html.haml', status: 200 }
    end
end

def call_search_in_doctor(keyword)
  Doctor.search keyword,
                misspellings: { edit_distance: 3 },
                page: params[:page],
                per_page: 10,
                limit: 100,
                fields: [{ name: :word },
                         { name: :word_start },
                         { name: :word_middle },
                         { name: :word_end },
                         :code, :field_name]
end

这是我的控制器测试:

context 'with keyword' do
  let(:search_param) { "rizky" }
  let(:doctor) { instance_double(Doctor) }
  let(:results) { instance_double(Searchkick::Results) }

  before do
    allow(Doctor).to receive(:search).with(search_param) {:results}
  end

  it 'calls Doctor.search' do
    get :search, search_param
    expect(Doctor).to receive(:search).with(search_param)
  end
end

感谢您宝贵的时间!

【问题讨论】:

    标签: ruby-on-rails rspec rspec-rails searchkick rspec-mocks


    【解决方案1】:

    RSpec 并不是说​​没有调用Doctor.search,而是说没有使用您指定的参数调用它。您的生产代码调用 Doctor.search 时带有两个参数(搜索词和参数哈希),但您的测试允许 Doctor.search 仅使用一个参数(搜索词)调用。

    你可以修复它

    • 将第二个参数添加到您的测试中的with 调用(如果您认为检查该哈希是什么与测试相关),或者
    • 在这些调用中添加anything 的第二个参数(如果您认为哈希与测试无关而只想忽略它)

    【讨论】:

    • 谢谢!你是对的。这也是我的错误,其他错误是:1.我应该把get放在expect之后。 2. 由于我使用的是查询字符串,所以我应该输入 get :search, keyword: searchparam
    猜你喜欢
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 2013-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-08
    • 1970-01-01
    相关资源
    最近更新 更多