我現在正在爲控制器SearchController
製作Rspec。這個控制器通過使用「get」請求得到的參數來執行sql的搜索記錄。控制器如下。Rspec錯誤 - NoMethodError:未定義的方法`空?'
class SearchController < ApplicationController
def index
if params[:category] == 'All'
@search_result = Item.find_by_sql("SELECT * FROM items WHERE name LIKE '%# {params[:name]}%'")
else
@search_result = Item.find_by_sql("SELECT * FROM items WHERE name LIKE '%#{params[:name]}%' AND category = '#{params[:category]}'")
end
if @search_result.empty? then
redirect_to main_app.root_path, notice: "No items found matching your search criteria ! Modify your search."
else
@[email protected]_result.paginate(:page => params[:page],:per_page => 3)
end
end
end
然後我寫了如下簡單的Rspec測試。該測試旨在首先將對象item
用於控制器中。還聲明瞭存根(Item.stub(:find_by_sql).and_return(item)
)。然後用參數:category => 'All'
做get :index
。我的期望是,在控制器if params[:category] == 'All'
通過和@search_result
是由對象填充。 (正如我所提到,短線已經宣佈。此外對象是已經取得。然後Item.find_by_sql(*****)
將返回這是已經聲明的對象。)
require 'spec_helper'
describe SearchController do
let(:valid_session) { {} }
describe "" do
it "" do
item = Item.new(auction_id:'1',min_bid_price:'100.0')
item.save
Item.stub(:find_by_sql).and_return(item)
get :index, {:category => 'All'}, valid_session
@search_result.should_not be_empty
end
end
end
然後我跑了Rspec的,不幸的是得到了錯誤如下。我認爲@search_result
無法成功填充對象,所以「空?」無法呼叫。不過,我不知道如何解決這個問題。我已經用了很多時間了。我想找人幫忙。
Failures:
1) SearchController
Failure/Error: get :index, {:category => 'All'}, valid_session
NoMethodError:
undefined method `empty?' for #<Item:0x523c980>
# ./app/controllers/search_controller.rb:9:in `index'
# ./spec/controllers/search_controller_spec.rb:13:in `block (3 levels) in <top (required)>'
Finished in 0.25 seconds
1 example, 1 failure
Failed examples:
rspec ./spec/controllers/search_controller_spec.rb:8 # SearchController
Randomized with seed 50151
最後它工作。謝謝PinnyM! – Tom0728