我的模型中定义了以下搜索功能:
class CoffeeType < ActiveRecord::Base
has_many :coffee_items
def self.search(search)
if search
where('name LIKE ?', "%#{search}")
else
where(nil)
end
end
end
并进行以下RSpec测试:
describe "GET index with serach params" do
it 'renders a list of Coffee Types' do
get :index, {search: "Ame"}, valid_session
assigns(:coffee_types).count.should eq(2)
end
end
这可能非常微不足道,我在这里看不到更大的图景。
答案 0 :(得分:0)
有关默认rspec use_transactional_fixtures
设置的说明,请参阅此处:
https://www.relishapp.com/rspec/rspec-rails/docs/transactions
除非您更改了此配置,否则在每个示例后都会重置数据库。因此,您需要在示例/示例组中实际设置初始状态。在您的情况下,可能看起来像:
describe "GET index with serach params" do
before :each do
# create two coffee_types that should be found by searching for "Ame" and
# one that shouldn't
2.times { FactoryGirl.create :coffee_type }
FactoryGirl.create :coffee_type, name: "Espresso"
end
it 'renders a list of Coffee Types' do
get :index, {search: "Ame"}, valid_session
assigns(:coffee_types).count.should eq(2)
end
end
编辑:Duh!实际上,模型方法中的代码不正确。在搜索字词之前,您只获得了%
通配符。将该行更改为:
where('name LIKE ?', "%#{search}%")