2012-04-17 23 views
3

我收到試圖用Draper測試時,出現以下錯誤:德雷珀 - NoMethodError使用RSpec測試裝飾

NoMethodError: undefined method 'with_unit' for nil:NilClass 

這裏是我的測試代碼:

# spec/decorators/food_decorator_spec.rb 
require 'spec_helper' 

describe FoodDecorator do 
    before { ApplicationController.new.set_current_view_context } 
    FactoryGirl.create(:food) 
    @food = FoodDecorator.first 

    specify { @food.with_unit('water').should == "85.56 g" } 
end 

這是我的裝飾器的代碼:

class FoodDecorator < ApplicationDecorator 
    decorates :food 

    def with_unit(nutrient) 
    model.send(nutrient.to_sym).to_s + " g" 
    end 
end 

我的研究表明該行ApplicationController.new.set_current_view_context sho uld解決這個問題,但它沒有。有什麼想法嗎?

回答

3

替換爲:

require 'spec_helper' 

describe FoodDecorator do 
    before do 
    ApplicationController.new.set_current_view_context 
    FactoryGirl.create(:food) 
    @food = FoodDecorator.first 
    end 

    specify { @food.with_unit('water').should == "85.56 g" } 
end 

你甚至可以這樣做:

require 'spec_helper' 

describe FoodDecorator do 

    let(:food) { Factory(:food) } 
    subject { FoodDecorator.first } 

    before do 
    food 
    ApplicationController.new.set_current_view_context 
    end 

    specify { subject.with_unit('water').should == "85.56 g" } 
end 
+0

也沒有工作,但你能解釋一下我哪裏錯了?謝謝:) – Nick 2012-04-17 18:29:50

+1

您的工廠沒有包含在您的前塊,只是:) – apneadiving 2012-04-17 18:30:26

+0

我遇到'主題{FoodDecorator.first}'行的第二個代碼塊的問題'FactoryGirl.create'行有尚未運行。我懷疑這是由於用'let'語句來記憶。由於工廠尚未運行,「FoodDecorator.first」返回'nil'。刪除'let'部分並僅將其保留爲'FactoryGirl.create(:food)'修復此問題。任何關於如何解決這個問題的想法,或者我目前的解決方案是否可以接受? – Nick 2012-04-25 19:40:56