我有以下控制器操作:
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
测试此方法的正确方法是什么?谢谢!
答案 0 :(得分:0)
@companies
而非Company
正在接收:where
在测试代码中,您必须以实际代码Company
从@companies
下降的方式显示模拟从Company
下降的方式。这是必要的,以使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
你问过一段时间了。希望你会发现它很有用。