2012-04-26 50 views
0

我的應用程序工作正常,但我無法通過測試。如果答案是顯而易見的,我是新手,所以原諒我。應用程序變量在測試環境中爲零

我需要每一個視圖中可用的變量,所以我這樣做內application_controller.rb

class ApplicationController < ActionController::Base 
    protect_from_forgery 
    before_filter :course 
    def course 
    @course = Course.find_slug(params[:course]) 
    end 
end 

我的測試情況是這樣的:

it "creates an attempt" do 
    sign_in current_user 
    params = {:id => challenge.id, :description => "this was hard!", :course => "design"} 
    @course = FactoryGirl.create(:course) 
    post :completed, params 
    response.should redirect_to "/#{@course.slug}/?challenge_slug=" + challenge.slug 
    Attempt.count.should == 1 
    Attempt.last.description.should == params[:description] 
end 

我的控制器內的方法看起來像這樣的:

def completed 
    @challenge = Challenge.find(params[:id]) 
    @challenge.completed(current_user, params) 
    redirect_to "/#{@course.slug}/?challenge_slug=" + @challenge.slug.to_s 
    end 

所有這一切,如果我使用的應用A工作正常N,但測試說:

1) ChallengesController completing a challenge creates an attempt 
    Failure/Error: post :completed, params 
    NoMethodError: 
     undefined method `slug' for nil:NilClass 
    # ./app/controllers/challenges_controller.rb:16:in `completed' 
    # ./spec/controllers/challenges_controller_spec.rb:36:in `block (3 levels) in <top (required)>' 

如果我硬編碼我控制器說redirect_to "#{'expected_value'}",則測試通過,所以它似乎在測試環境中,我沒有訪問應用程序變量@course,這是正確的?

我迷失在如何解決這個問題。任何幫助表示讚賞。

回答

1

一個解決方案是存根find方法並返回實例變量。

before(:each) do 
    @course = FactoryGirl.create(:course) 
    Course.stub(:find_slug).and_return(@course) 
end 

這使得你的測試更健壯的測試「find_slug」應該是在你的課程模式,而不是控制。

+0

啊,我明白了!謝謝! – Duopixel 2012-04-26 06:14:31

相關問題