diff --git a/lib/api.rb b/lib/api.rb index a8d499c..6cdcbdc 100644 --- a/lib/api.rb +++ b/lib/api.rb @@ -8,12 +8,17 @@ class Api def self.search_by_title(title) url = "http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=#{APIKEY}&q=#{URI.encode(title)}&page_limit=1" - struct = OpenStruct.new(get_url_as_json(url).fetch("movies").first) - Movie.new(id: struct.id.to_i, - title: struct.title, - year: struct.year, - score: struct.ratings["critics_score"] - ) + begin + struct = OpenStruct.new(get_url_as_json(url).fetch("movies").first) + Movie.new(id: struct.id.to_i, + title: struct.title, + year: struct.year, + score: struct.ratings["critics_score"] + ) + rescue + #raise ArgumentError, "invalid movie #{title.strip} given" + return :no_movie_found + end end diff --git a/movie_json.rb b/movie_json.rb index d8a91d7..361b2c0 100644 --- a/movie_json.rb +++ b/movie_json.rb @@ -2,10 +2,14 @@ require_relative "lib/api" def find_movie - puts "OH HAI. Search?" + puts "OH HI. Search?" movie_title = gets movie = Api.search_by_title(movie_title) - puts "Found: #{movie.title}. Score: #{movie.score}" + if movie == :no_movie_found + puts "Invalid movie title : #{movie_title.strip}" + else + puts "Found: #{movie.title}. Score: #{movie.score}" + end end find_movie diff --git a/spec/api_spec.rb b/spec/api_spec.rb index 9014106..7af3668 100644 --- a/spec/api_spec.rb +++ b/spec/api_spec.rb @@ -3,25 +3,48 @@ describe Api do - let(:movie) { Api.search_by_title("Forrest Gump") } + context "valid movie title" do - before do - Api.stub(:get_url_as_json) { JSON.parse(File.read("spec/fixtures/forrest.json")) } - end + let(:movie) { Api.search_by_title("Forrest Gump") } - it "should search for movies" do - movie.title.should eq("Forrest Gump") - end + before do + expect { + Api.stub(:get_url_as_json) { JSON.parse(File.read("spec/fixtures/forrest.json")) } + }.to_not raise_error + end - it "should return the score" do - movie.score.should eq(71) - end + it "should search for movies" do + movie.title.should eq("Forrest Gump") + end + + it "should return the score" do + movie.score.should eq(71) + end + + it "should return the id" do + movie.id.should eq(10036) + end + + it "should return the year" do + movie.year.should eq(1994) + end - it "should return the id" do - movie.id.should eq(10036) end - it "should return the year" do - movie.year.should eq(1994) + context "invalid movie title" do + let(:movie) { Api.search_by_title("hgh") } + + before do + expect { + Api.stub(:get_url_as_json) { JSON.parse(File.read("spec/fixtures/invalid.json")) } + }.to_not raise_error + end + + it "should return :no_movie_found" do + movie.should eq(:no_movie_found) + end + end + + end