2013-09-26 150 views
0

我在這個測試中得到undefinded local variable or method user。任何人幫助?Rspec'範圍之前的範圍

context "[user IS signed in]" do  
    before do 
     user = Fabricate(:user) 
     league = Fabricate(:league) 
     event = Fabricate(:event, league: league) 
     @request.env["devise.mapping"] = Devise.mappings[:user] 
     sign_in user 
     ApplicationController.any_instance.stub(:primary_leagues).and_return([league]) 
    end 

    it "[creates a pick for a user]" do 
    post 'create', {:pick => {user_id: user.id, event_id: event.id, league_id: league.id, points_pick: "home"}} 
    Pick.all.size.should eq(1) 
    end 

回答

2

before塊聲明user作爲一個局部變量,因此超出範圍的it塊中。

解決此問題的最簡單方法是在before塊中聲明成員變量,例如,

before do 
    @user = Fabricate(:user) 
    @league = Fabricate(:league) 
    @event = Fabricate(:event, league: @league) 
    ... 
end 

it "[creates a pick for a user]" do 
    post 'create', {:pick => {user_id: @user.id, event_id: @event.id, league_id: @league.id, points_pick: "home"}} 
    Pick.all.size.should eq(1) 
end 

此操作,因爲beforeit在相同的(生成的)類實例的上下文中執行。

或者,您可以用let聲明您的變量,並保留原樣的代碼示例。

context "[user IS signed in]" do  
    let(:user) { Fabricate(:user) } 
    let(:league) { Fabricate(:league) } 
    let(:event) { Fabricate(:event, league: league) } 

    before do 
    @request.env["devise.mapping"] = Devise.mappings[:user] 
    sign_in user 
    ApplicationController.any_instance.stub(:primary_leagues).and_return([league]) 
    end 

    it "[creates a pick for a user]" do 
    post 'create', {:pick => {user_id: user.id, event_id: event.id, league_id: league.id, points_pick: "home"}} 
    Pick.all.size.should eq(1) 
    end 

let將實例給定的變量,當它第一次被引用和memoize的結果。