2011-07-19 97 views
1

我想測試下的輔助模塊功能:無法從輔助模塊訪問IMAGE_TAG

module UploadsHelper 

    def custom_img_tag(upload, width, height, id) 
    if width > Upload::MAX_CROP_WIDTH 
     image_tag(upload.photo.url(:original), :id => "box", :width => Upload::MAX_CROP_WIDTH, :height => (height*Upload::MAX_CROP_WIDTH/width).to_i) 
    else 
     image_tag(upload.photo.url(:original), :id => "box") 
    end 
    end 

end 

然而,當我運行下面的測試:

describe UploadsController do 
    include UploadsHelper 
    describe "custom_img_tag(upload, width, height, id)" do 
      before(:each) do 
      @upload = Factory(:upload) 
      geo = Paperclip::Geometry.from_file(@upload.photo.to_file(:original)) 
      @width = geo.width 
      @height = geo.height 
      end 

     it "should return the original image tag for an image that is not wider than MAX_CROP_WIDTH" do 
     #custom_img_tag(@upload,@width, @heigth, "cropbox").should == '<img id="cropbox" width="500" height="375" src="/system/photos/10/original/avatar.jpg?1311044917" alt="Avatar" style="display: none;">' 
     end 
    end 

我得到以下錯誤:

Failure/Error: custom_img_tag(@upload,@width, @heigth, "cropbox").should == '<img id="cropbox" width="500" height="375" src="/system/photos/10/original/avatar.jpg?1311044917" alt="Avatar" style="display: none;">' 
    NoMethodError: 
     You have a nil object when you didn't expect it! 

爲什麼我得到這個錯誤,我該如何測試這個方法?

更新: 添加以下的規範測試文件:

include ActionView::Helpers 

將會產生以下錯誤:

NameError: 
     undefined local variable or method `config' for #<RSpec 

我怎樣才能擺脫這種錯誤的和的原因是什麼?

感謝您的任何幫助。

+0

你的'Factory:upload'是什麼樣的? '你有一個無對象'是一個非常簡單的錯誤信息......'custom_img_tag'方法中的哪些對象是nil? – Andrew

+0

順便說一句,你可以通過放置'puts @ upload.inspect'或類似的東西來快速檢查一個規範內的東西。當你運行規範時它會打印到控制檯。之後不要把它留在那裏,但是我發現當規範行爲奇怪時,有時可以幫助定位問題。 – Andrew

+0

謝謝安德魯我會看看並使用它。我非常感謝你的幫助。 – chell

回答

3

我也腹背受敵與Rails的3.1 RC

NameError: 
    undefined local variable or method `config' 

一些Rails的溯源工作的錯誤,我發現了丟失的包括::的ActionView AssetPaths。

include ActionView::AssetPaths 
include ActionView::Helpers::AssetTagHelper 
+0

按照http://stackoverflow.com/questions/6290176/helper-method-included-in-a-model-produces-undefined-local-variable-or-method,「AssetPaths」現在是一個類,所以你不能像這樣包括它。 –

0

嗯,我不知道這是爲什麼,但我的猜測是,由於某種原因,ActionView :: Helpers一定不能在本規範中加載。嘗試包括ActionView :: Helpers,看看是否修復它...問題(從你報告的是)當你的custom_img_tag方法被稱爲它不能因爲某種原因調用image_tag

+0

嗨安德魯。我包含了ActionView :: Helpers,現在當我運行測試時,我得到這個錯誤:NameError: 未定義的局部變量或方法'配置'爲# chell

+0

對不起,我不知道會觸發什麼。我絕對不是RSpec專家。這個問題可能需要獲得回報。 – Andrew

+0

謝謝,我會考慮這一點。 – chell