2015-09-28 94 views
1

在控制器中,它不分配任何變量來查看。但是在Rspec測試中變量總是被賦值。Rspec,意外變量分配

訂單#指數

# GET /orders 
# GET /orders.json 
def index 
    respond_to do |format| 
    format.html { render :app } 
    # format.json { @orders = Order.all.order('created_at desc'); puts 'run'} 
    end 
end 

orders_spec.rb

describe "GET #index" do 
    it "assigns all orders as @orders" do 
    order = Order.place_order valid_attributes 
    puts order 
    # get :index, format: :json 
    # expect(assigns(:orders)).to eq([order]) 
    get :index, format: 'html' 
    expect(assigns(:orders)).to eq(nil) 
    end 
end 

結果:

Failures: 

1) OrdersController GET #index assigns all orders as @orders 
    Failure/Error: expect(assigns(:orders)).to eq(nil) 

    expected: nil 
      got: #<ActiveRecord::Relation [#<Order id: 1, user_id: 1, price: #<BigDecimal:7f9e57da2f30,'0.999E3',9(27)>, created_at: "2015-09-28 04:44:10", updated_at: "2015-09-28 04:44:10", uid: "150928120001">]> 

    (compared using ==) 
    # ./spec/controllers/orders_controller_spec.rb:54:in `block (3 levels) in <top (required)>' 
+1

你使用康康還是學者?訂單控制器中是否有過濾器? –

回答

1

不知怎的,在你的代碼,orders越來越填充爲html模板。可能你有一個before_filter或別的東西(例如,load_and_authorize_resource,如果你使用cancancan)總是分配orders而不考慮格式。請確保情況並非如此。

+0

謝謝,我試過了。得到相同的結果。 – emj365

+0

請看我更新的答案。如果沒有看到完整的應用程序代碼,真的很難說。你能告訴我們控制器的完整代碼嗎? –

+1

我刪除了Cancancan的'load_and_authorize_resource'。 '@orders == nil'現在。 – emj365