2011-06-10 112 views
7

給定一個像這樣的控制器,它可以創建多個實例變量以供視圖使用,您通常會測試每個變量是否設置正確?這看起來像你想要的,但它似乎也有點可能有點棘手。什麼是正確的方法?使用RSpec測試控制器中的實例變量

class StaffsController < ApplicationController 

    def index 
    set_index_vars 
    @all_staff = Staff.find_staff_for_business_all_inclusive(current_business_id) 
    respond_to do |format| 
    format.html { render :action => "index", :locals => { :all_staff => @all_staff, :all_services => @all_services, :new_vacation => @new_vacation } } 
    end 
    end 

    def set_index_vars 
    @days_of_week = days_of_week 
    @first_day_of_week = DefaultsConfig.first_day_of_week 

    @all_services = Service.services_for_business(current_business_id) 

    @new_vacation = StaffVacation.new 
    @has_hit_staff_limit = current_user_plan.has_hit_staff_limit? 
    end 

end 

的代碼也張貼在https://gist.github.com/1018190

回答

11

如果你打算編寫一個控制器規範,那麼是的,所有的意思都是測試實例變量的分配。大部分「trickiness」可以來自其他型號/庫的依賴關係,因此,踩滅了那些方法調用:

# air code 
Staff.stub(:find_staff_for_business_all_inclusive) {array_of_staff} 
controller.stub(:days_of_week) {['Monday','Tuesday',....etc...]} 
DefaultsConfig.stub(:first_day_of_week) {"Monday"} 
Service.stub(:services_for_business).with(some_value_for_the_current_business_id).\ 
    and_return(some_relevant_value) 
StaffVacation.stub(:new) {something_meaningful} 
controller.stub_chain(:current_user_plan,:has_hit_staff_limit?) {false} 

get :index 
assigns(:days_of_week).should == ['Monday','Tuesday',....etc...] 
# ...etc... 
0

只要您對您的方法,良好的覆蓋,你可以測試你的方法被調用在正確的時間,用正確的價值觀等等東西比如:

describe StaffsController do 
    describe "GET #index" do 
    it "should call set_index_vars" do 
     controller.should_receive(:set_index_vars) 
     get :index 
    end 
    end 

    describe "#set_index_vars" do 
    it "should assign instance variables with correct values" do 
     # or wtv this is supposed to do 
     get :index 
     assigns(:days_of_week).should == controller.days_of_week 
     # etc .. 
    end 
    end 
end 
1

如下我將它分解:測試的index調用正確的方法。然後測試該方法是否有效。

因此,像

describe StaffsController do 
    describe "GET #index" do 
    it "calls set_index_vars" do 
     controller.should_receive(:set_index_vars) 
     get :index 
    end 
    # and your usual tests ... 
    end 

    describe "#set_index_vars" do 
    before(:each) do 
     # stub out the code not from this controller 
     controller.stub_chain(:current_user_plan, :has_hit_staff_limit?).and_return(false) 
     .. etc .. 

     controller.set_index_vars 
    end 
    it { assigns(:days_of_week).should == controller.days_of_week } 
    it { assigns(:has_hit_staff_limit).should be_false 
    # etc .. 
    end 
end 

希望這有助於。