Rspec controller test, trying to create a test for a 'processlogin' action
My create user method in the users_controller.rb looks like:
def process_login
is_login_valid(params[:user][:user_name], params[:user][:password])
if logged_in?
redirect_to root_url
else
@user = User.new(params[:user][:user_name]
redirect_to :action => 'login'
end
What I have currently:
describe UsersCon开发者_JAVA百科troller do
describe "Post 'process_login'"
it "should be successful" do
post 'process_login'
response.should be_success
end
end
end
The methods is_login_valid and logged_in? are all included in the application_controller, and are methods from a ruby class I have in my /lib folder called LoginSystem.rb
My test is failing since it isn't mocking things correctly, this is my first time doing this so hoping someone can help me out.
Error message:
UsersController POST 'process_login' should be successful
Failure/Error: post 'process_login'
NoMethodError:
You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.[]
# ./app/controllers/users_controller.rb:11:in `process_login'
# ./spec/controllers/users_controller_spec.rb:21
Aah, Thanks for the error message. I'm assuming that line 11 is is_login_valid(params[:user][:user_name], params[:user][:password])
.
As you're not sending any params in your test post params[:user] is nil hence the nil.[] error (when the controller is looking for params[:user][:user_name]), you set params by passing them as a hash as the 2nd parameter to post in your test.
I think you actually need
controller.stub(:logged_in?) { true }
Or if you want to test that the logged_in method is actually being called
controller.should_receive(:logged_in?).and_return(true)
The 2nd version will cause the test to fail unless the method logged_in?
is called once and only once
You may also need the controller.stub(:is_login_valid} { true }
as suggested by @jaydel if you're getting an error message about this method being missing as well
I believe:
controller.stub(:is_login_valid} { true }
should get you where you want to go, if I understand correctly.
精彩评论