2016-08-04 132 views
0

目前,我有我的控制器以下自定義操作:Rspec的3 - 測試在指定的控制器動作

def set_active 
    current_user.active_meal_plan = @meal_plan 
    current_user.save 

    respond_with @meal_plan, location: -> { meal_plans_path } 
end 

控制器行動工作,它的預期。但是,如何使用Rspec測試current_user.active_meal_plan = @meal_plan部件,我有點不知所措。

這是我的測試看起來像:

RSpec.describe MealPlansController, type: :controller do 
    let(:user) { FactoryGirl.create(:user, :admin) } 

    before :each do 
    # Sign in with Devise as an admin user 
    @request.env["devise.mapping"] = Devise.mappings[:admin] 
    sign_in user 

    # Bypass CanCan's authorization 
    allow_any_instance_of(CanCan::ControllerResource).to  receive(:load_and_authorize_resource){ nil } 
    end 

    # ... 

    describe "PUT #set_active" do 
    let(:meal_plan) { FactoryGirl.create(:meal_plan, user: user) } 

    it "assigns the requested meal plan to @meal_plan" do 
     put :set_active, id: meal_plan 
     expect(assigns(:meal_plan)).to eq(meal_plan) 
    end 

    it "sets the requested meal plan as the user's active meal plan" do 
     put :set_active, id: meal_plan 
     expect(assigns(user.active_meal_plan)).to eq(meal_plan) 
    end 

    it "redirects to the meal plans view" do 
     put :set_active, id: meal_plan 
     expect(response).to redirect_to meal_plans_path 
    end 
    end 

所有的測試都通過不同的是二次之一。

這裏是我的用戶模型:

class User < ActiveRecord::Base 
    # .. 
    has_many :meal_plans, dependent: :destroy 
    belongs_to :active_meal_plan, class_name: 'MealPlan' 
end 

我的用戶廠:

FactoryGirl.define do 
    factory :user do 
     first_name 'John' 
     last_name 'Doe' 
     address 'San Francisco Bay Area' 
     email { Faker::Internet.email } 
     password "password" 
     password_confirmation "password" 
     pricing_plan { FactoryGirl.create(:pricing_plan) } 
     active_meal_plan nil 
    end 

    trait :user do 
     after(:create) {|user| user.add_role(:user)} 
    end 

    trait :admin do 
     after(:create) {|user| user.add_role(:admin)} 
    end 
end 

而且,顯然assigns將在Rails的5其實,controller tests will be removed棄用。從我所收集的,根據討論,似乎我不應該測試這樣的事情....

反正,我想使這個測試通過。

回答

0

幫手assigns實際上會獲取ivar,如@meal_plan,但current_user不是一個ivar,而是一個方法。

這是我會怎麼測試:

it "sets the requested meal plan as the user's active meal plan" do 
    put :set_active, id: meal_plan 
    expect(user.reload.active_meal_plan).to eq(meal_plan) 
end 
+0

完美的作品!謝謝! – Andres