Jef*_* W. 131 ruby testing rspec ruby-on-rails devise
我的大多数测试都提出了以下内容,我不明白为什么.所有方法调用都会引发"authenticate"错误.我检查了代码是否有一个名为"authenticate"的方法,但没有这样的方法.
1) Admin::CommentsController handling GET to index is successful
Failure/Error: get :index
undefined method `authenticate!' for nil:NilClass
# ./spec/controllers/admin/comments_controller_spec.rb:9:in `block (3 levels) in <top (required)>'
124) PostsController handling GET for a single post should render show template
Failure/Error: get :show, :year => '2008', :month => '01', :day => '01', :slug => 'a-post'
undefined method `authenticate' for nil:NilClass
# ./app/controllers/application_controller.rb:18:in `set_current_user_for_model'
# ./spec/controllers/posts_controller_spec.rb:131:in `do_get'
# ./spec/controllers/posts_controller_spec.rb:140:in `block (3 levels) in <top (required)>'
Run Code Online (Sandbox Code Playgroud)
该项目可以在那里找到=> https://github.com/agilepandas/enki,以防你想自己运行测试.
Jef*_* W. 191
@MatthewClosson在推特上回答了这个问题
@jeffehh您需要创建一个spec/support/devise.rb文件,如https://github.com/plataformatec/devise#test-helpers所示,包括设计测试助手#ruby
再次感谢.
Tim*_*her 73
我知道你正在使用Rspec,但你可能遇到同样的问题Test::Unit.您只需要添加设计测试助手即可test/test_helper.rb
class ActiveSupport::TestCase
include Devise::TestHelpers
end
Run Code Online (Sandbox Code Playgroud)
以上答案对我不起作用(RSpec 3.1)
有关适用于我的解决方案,请访问/sf/answers/1481653771/.
在设置变量之前,您需要注销匿名用户:
before :each do
sign_out :user
end
Run Code Online (Sandbox Code Playgroud)
在RSpec
正如Jeffrey W.在上面的回答中提到的那样 - >将其设置为所有控制器:
RSpec.configure do |config|
# ...
config.include Devise::TestHelpers, type: :controller
# ...
end
Run Code Online (Sandbox Code Playgroud)
但是,如果这只与一个规范相关,那么您不一定需要在所有控制器规范中包含设计帮助程序,您可以在该控制器描述块中明确包含这些帮助程序:
require 'spec_helper'
describe MyCoolController
include Devise::TestHelpers
it { }
end
Run Code Online (Sandbox Code Playgroud)