0

I am learning rspec and databases and have one movie database with the following schema. I'd like to know how to get this test to pass since my efforts seem to be futile. If you need any additional info please let me know in case I'm leaving something vital out that would be helpful:

Schema

 create_table "movies", force: true do |t|
   t.string   "title",      null: false
   t.integer  "year",       null: false
   t.text     "synopsis"
   t.integer  "rating"
   t.datetime "created_at"
   t.datetime "updated_at"
   t.integer  "genre_id",   null: false
   t.in
end

create_table "genres", force: true do |t|
    t.string   "name",       null: false
    t.datetime "created_at"
    t.datetime "updated_at"
  end

Model setup:

class Movie < ActiveRecord::Base
  validates_presence_of :title
  validates_presence_of :year
  validates_presence_of :genre

  has_many :cast_members
  has_many :actors, through: :cast_members

  belongs_to :genre
  belongs_to :studio

Rspec test:

it "partially matches movie titles" do
  results = Movie.search('Manhat')

  expect(results.count).to eq(2)
  expect(results.include?(manhattan)).to be_true
  expect(results.include?(mystery)).to be_true
end

Rspec test argument input:

.create(:movie, title: "Manhattan Murder Mystery"

Code I've tried several variations of so far:

class Movie < ActiveRecord::Base

etc, above..

def self.search(query)  
  select('title').where('title ilike ? OR synopsis ilike ?','%query%', '%query%')
end
zishe
  • 10,665
  • 12
  • 64
  • 103
John
  • 443
  • 8
  • 19

1 Answers1

1

You are not passing the parameter to the query. You are always searching for results containing "query". What you should do is:

select('title').where('title ilike ? OR synopsis ilike ?',"%#{query}%", "%#{query}%")

This will substitute the "#{query}" with the parameter passed to the search method.

mechanicalfish
  • 12,696
  • 3
  • 46
  • 41
  • 1
    Or `where('title ilike :pat or synopsis ilike :pat', :pat => "%#{query}%")`. – mu is too short Dec 15 '13 at 02:20
  • @muistooshort thanks, that's quite useful. Do you know an easy alternative so % and other LIKE syntax will be escaped? – mechanicalfish Dec 15 '13 at 02:34
  • AFAIK you're always responsible for dealing with embedded `%` and `_` yourself. I could be wrong of course, it isn't like you can easily look this stuff up without a side adventure through the Rails source code. – mu is too short Dec 15 '13 at 03:10
  • Thanks for the suggestion I'll keep that in mind. Tried it out and the test is still failing though – John Dec 15 '13 at 04:01
  • @mechanicalfish I updated the question with the definitions (if I am understanding correctly). They are directly under the spec section of my question: .create(:movie, title: "Manhattan Murder Mystery") – John Dec 15 '13 at 13:57
  • Tried the solution from @mu is too short and it worked, thanks for the help you guys. – John Dec 15 '13 at 16:34