2013-11-22 45 views
0

我現在正在爲控制器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 

回答

4

的問題是在這裏:

Item.stub(:find_by_sql).and_return(item) 

你是磕碰的find_by_sql並返回一個單一的項目,而不是項目的集合。簡單的解決方法是把它包在一個數組:

Item.stub(:find_by_sql).and_return [item] 

注意,如果數組被修改,以支持paginate(will_paginate會做,如果你需要`will_paginate /陣列」庫),這隻會工作。

從這個

除此之外,作爲@PeterAlfvin已經提到的,你有你附近的規範結尾的錯誤:

@search_result.should_not be_empty 

實際上應該寫成:

assigns(:search_result).should_not be_empty 

這是因爲你可以不直接訪問由控制器操作分配的實例變量。

+0

最後它工作。謝謝PinnyM! – Tom0728

1

雖然錯誤發生在您的模型中,但您的示例中也存在問題。

您似乎認爲,因爲@search_result在控制器中定義,所以可以在您的RSpec示例中直接訪問。事實並非如此。 @search_result在示例中爲nil,因爲您尚未爲其分配值。

可以,但是,訪問@search_result實例變量在所述控制器通過所述RSpec的assigns方法,如在assigns[:search_result]

+0

在給出的例子中,它不是零 - 它是一個Item。 – PinnyM

+0

???怎麼樣? 「Item」唯一的就是'item',我可以看到。 –

+0

具體的錯誤消息是:「未定義的方法」爲空?爲#'。這個問題是由於我的答案中寫下來的殘片。 – PinnyM

相關問題