users_controller.rb中的我的create user方法如下所示:
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
我目前的情况:
describe UsersController do
describe "Post 'process_login'"
it "should be successful" do
post 'process_login'
response.should be_success
end
end
end
方法is_login_valid和logged_in?都包含在application_controller中,并且是来自我/ lib文件夹中名为LoginSystem.rb的ruby类的方法
我的测试失败,因为它没有正确地嘲笑事情,这是我第一次这样做,所以希望有人可以帮助我。
错误讯息:
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
答案 0 :(得分:2)
啊,谢谢你的错误信息。我假设第11行是is_login_valid(params[:user][:user_name], params[:user][:password])
。
由于你没有在你的测试帖中发送任何参数params [:user]为零因此nil。[]错误(当控制器正在寻找params [:user] [:user_name])时,你设置了params将它们作为哈希作为第二个参数传递给你在测试中发布。
答案 1 :(得分:1)
我认为你确实需要
controller.stub(:logged_in?) { true }
或者,如果您想测试实际调用logged_in方法
controller.should_receive(:logged_in?).and_return(true)
第二个版本将导致测试失败,除非方法logged_in?
被调用一次且仅一次
如果您收到有关此方法丢失的错误消息,您可能还需要@jaydel建议的controller.stub(:is_login_valid} { true }
答案 2 :(得分:0)
我相信:
controller.stub(:is_login_valid} { true }
如果我理解正确,应该可以让你到达目的地。