2017-07-09 2 views
2

Ich habe ein Problem mit RSPC Stubbing. Ich verfolge dieses doc https://relishapp.com/rspec/rspec-mocks/docs/working-with-legacy-code/any-instanceRspec Stub funktioniert nicht, wenn innerhalb eines vor-Block aufgerufen

describe Api::V1::ActionsController, type: :controller do 
    let(:admin) { create :admin } 

    subject { response } 

    describe 'GET #index' do 
    before :each do 
     get :index 
    end 

    context 'admin' do 
     before :each do 
     allow_any_instance_of(ApplicationController).to receive(:current_user).and_return admin 
     allow_any_instance_of(ApplicationController).to receive(:authenticate!).and_return true 
     end 

     it 'expects 200' do 
     expect(response.status).to eq 200 
     end 
    end 
    end 

Dieser Test schlägt fehl. Und das Interessante ist, dass, wenn ich diese Stubs spec_helper.rb setzen wie

config.before :each do 
    allow_any_instance_of(ApplicationController).to receive(:current_user).and_return admin 
    allow_any_instance_of(ApplicationController).to receive(:authenticate!).and_return true 
    end 

es funktioniert gut. Irgendwelche Ideen?

+0

Wo und wie haben Sie Ihre 'request' beschreiben? – spickermann

+0

Während Sie Ihre Frage nicht direkt beantworten, könnten Sie an [dieser Frage] interessiert sein (https://stackoverflow.com/questions/24522294/rspec-how-to-stub-inherited-method-current-user-wo-devise) über Stubbing 'current_user'. Antwort scheint immer noch zu funktionieren –

+0

@spickermann Ich habe meinen Eintrag aktualisiert. Es ist Controller-Spezifikation –

Antwort

3

I erraten, das Problem ist, dass dieses Stück Code:

before :each do 
    get :index 
end 

Läufe vor die Stubs:

before :each do 
    allow_any_instance_of(ApplicationController).to receive(:current_user).and_return admin 
    allow_any_instance_of(ApplicationController).to receive(:authenticate!).and_return true 
end 

before Blocks von außen nach innen geführt werden, und der Block mit den Stubs ist tiefer verschachtelt. Wenn Sie also die Methoden stubben, wurde get :index bereits ausgeführt.

diese stattdessen versuchen:

describe 'GET #index' do 
    subject do # define what `subject` will do, but don't actually run it just yet 
    get :index 
    end 

    context 'admin' do 
    before :each do 
     allow_any_instance_of(ApplicationController).to receive(:current_user).and_return admin 
     allow_any_instance_of(ApplicationController).to receive(:authenticate!).and_return true 
    end 

    it 'returns 200' do 
     expect(subject).to be_success 
     #  ^^^ now it's only here that the controller action is executed 
    end 
    end 
end 
+0

Absolut richtig :) Danke! –

Verwandte Themen