2017-07-25 99 views
0

我怎麼能翻番@user VAR方法中我怎樣才能加倍的變量,如果我不加倍,測試將拋出的零的在rspec的軌道

呼叫update_attributes方法錯誤:NilClass

class TestController 
    def foo! 
     @user = current_user 
     @user.update_attribute(user_params) 
    end 
end 

RSpec.describe TestController, type: :controller do 
    describe "#foo" do 
     it "should be passed" do 
      @specific_user = FactoryGirl.create(:user) 
      allow_any_instance_of(TestController).to receive(:foo!).and_return(true) 
      allow_any_instance_of(TestController).to receive(@user).and_return(@specific_user) 
     end 
    end 
end 

回答

1

你測試的問題是它沒有測試任何東西。控制器測試應該對測試方法get :foo!

關於磕碰,你的情況current_user方法的請求可以代替存根:

RSpec.describe TestController, type: :controller do 
    describe "#foo" do 
    it "should be passed" do 
     @specific_user = FactoryGirl.create(:user) 
     allow(controller).to receive(:foo!).and_return(true) 
     allow(controller).to receive(:current_user).and_return(@specific_user) 
    end 
    end 
end 

,是的,在控制器測試控制器實例可以通過訪問調用controller方法。

什麼也允許在該控制器設置一個實例變量:

RSpec.describe TestController, type: :controller do 
    describe "#foo" do 
    it "should be passed" do 
     @specific_user = FactoryGirl.create(:user) 
     allow(controller).to receive(:foo!).and_return(true) 
     controller.instance_variable_set(:@user, @specific_user) 
    end 
    end 
end