【问题标题】:Rspec cannot detect method call in activerecord method chainRspec 无法检测到 activerecord 方法链中的方法调用
【发布时间】:2015-07-22 23:36:00
【问题描述】:

我有以下控制器动作:

def index
    @companies = Company.order(:name).includes(:team_members, :user)

    if params[:search].present?
      @companies = @companies.where('name ilike ?', "%#{params['search']}%")
    end
end

以及相应的 rspec 测试:

before :each do
  allow(Company).to receive(:where)

  get :index, search: 'search_query'
end

it 'filters the companies by the search parameter' do
  expect(Company).to have_received(:where).with('name ilike "%search_query%"')
end

但是 rspec 没有检测到在 Company 类上调用了“where”方法。我收到以下错误:

1) CompaniesController GET #index when search parameter is given filters the companies by the search parameter
     Failure/Error: expect(Company).to have_received(:where).with('name ilike "%search_query%"')
       (Company(id: integer, name: string, description: text, season: string, iac_rating: float, funding_history: text, smart_scores: float, created_at: datetime, updated_at: datetime, logo: string, website: string, summary: text, pitch_deck: string, executive_summary: string, unique_factor: text, revenue_burn_rate: text, growth: text, category: string, typical_check_size: string, raising_amount: string, committed_amount: string, hq_location: string, sector: string, num_full_time_founders: string, user_id: integer, display_order: integer) (class)).where("name ilike \"%search_query%\"")
           expected: 1 time with arguments: ("name ilike \"%search_query%\"")
           received: 0 times

测试这个的正确方法是什么?谢谢!

【问题讨论】:

    标签: ruby-on-rails activerecord rspec


    【解决方案1】:

    收到的是 @companies 而不是 Company :where
    在您的测试代码中,您必须显示模拟如何从 Company 下降,就像在真实代码中 @companiesCompany 下降一样。这对于让 RSpec 匹配 @companies 及其各自的模拟 @companies_mock 是必要的。

      before :each do
        @companies_mock = double('Company')
        @intermediate_mock = double('Company')
    
        allow(Company).to receive(:order).and_return @intermediate_mock
        allow(@intermediate_mock).to receive(:includes).and_return @companies_mock
    
        allow(@companies_mock).to receive(:where)
    
        get :index, search: 'search_query'
      end
    
      it 'filters the companies by the search parameter' do
        expect(@companies_mock).to have_received(:where).with('name ilike ?', "%search_query%")
      end
    

    距离您的提问已经过去了一段时间。希望你会发现它有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多