如何在控制器中的搜索方法中存根Searchkick

时间:2016-03-12 09:16:24

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

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

Uncaught TypeError: Cannot read property 'set' of undefined

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

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

 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

这是我的控制器测试:

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

感谢您宝贵的时间!

1 个答案:

答案 0 :(得分:1)

RSpec并没有说babel-node ./node_modules/istanbul/lib/cli.js cover _mocha -- ./test 没有被调用,而是说没有用你指定的参数调用它。您的生产代码使用两个参数(搜索项和参数哈希)调用babel-node ./node_modules/istanbul/lib/cli.js cover _mocha -- ./test --require babel-polyfill \ --require should \ --require sinon ,但您的测试允许仅使用一个参数(搜索项)调用Doctor.search

您可以通过

修复它
  • 在测试中为Doctor.search调用添加第二个参数(如果您认为它与测试相关,以检查该哈希是什么),或者
  • 向这些调用添加Doctor.search的第二个参数(如果您认为散列与测试无关,只是想忽略它)