I have the following search function defined in my model:
class CoffeeType < ActiveRecord::Base
has_many :coffee_items
def self.search(search)
if search
where('name LIKE ?', "%#{search}")
else
where(nil)
end
end
end
and have the following RSpec test:
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
This is probably pretty much trivial and am not seeing the bigger picture here.
See here for an explanation of the default rspec use_transactional_fixtures
setting:
https://www.relishapp.com/rspec/rspec-rails/docs/transactions
Unless you've changed this configuration, your database is reset after every example. So you need to actually set up the initial state in the example/example group. In your case that might look something like:
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
Edit: Duh! Actually, the code in your model method is incorrect. You've only got the %
wildcard before the search term. Change that line to:
where('name LIKE ?', "%#{search}%")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.