RSpec Zugriff application_controller Methoden wie ‚current_user‘
-
03-10-2019 - |
Frage
Ich versuche, eine Methode auf meinem current_user Stub (unter Verwendung einer modifizierten restful_authentication Auth-Lösung) mit rspec. Ich bin völlig unsicher, wie ich diese Methode in meinen Controller-Spezifikationen zugreifen kann. current_user von selbst funktioniert nicht. Muss ich den Controller selbst zuerst bekommen? Wie kann ich das tun?
Mit rails 2.3.5
, rspec 1.3.0
und rspec-rails 1.3.2
# my_controller_spec.rb
require 'spec_helper'
describe MyController do
let(:foos){ # some array of foos }
it "fetches foos of current user" do
current_user.should_receive(:foos).and_return(foos)
get :show
end
end
Erzeugt
NoMethodError in 'ChallengesController fetches foos of current user'
undefined method `current_user' for #<Spec::Rails::Example::ControllerExampleGroup::Subclass_1::Subclass_1::Subclass_2::Subclass_2:0x7194b2f4>
Lösung
rspec-Schienen geben Ihnen ein controller
Verfahren zur Verwendung in der Steuerung Beispielen. Also:
controller.stub!(:current_user).with(:foos).and_return(foos)
sollte Arbeit.
Andere Tipps
how can it know where to find current_user
? this should solve it:
subject.current_user.should_receive(:foos).and_return(foos)
I'm not entirely familiar with restful_authentication, just Authlogic and Devise, but it's probably similar in that current_user
is a controller method and not an object, which is why calling should_receive
on it isn't working as expected (you're setting an expectation on the object that current_user
returns, but the method isn't accessible inside the scope of your expectation).
Try this:
stub!(:current_user).and_return(foos)
I read this and tweaked mine a bit. If you simply want to pass in a user object into your Rspec test, you can use this:
First, create a user object within the rspec test. For example: (use whatever attributes you need or are required to create the user object.)
user = User.create(name: "ted")
(Note: you can also use a factory from FactoryGirl.)
Now, with that user object which is saved into the variable "user", do this within that same Rspec test:
controller.stub!(:current_user).and_return(user)
that should work...