Making functional tests in Rails with Devise

送分小仙女□ 提交于 2019-12-20 09:17:14

问题


After 3 years of procrastination today is the day that I start testing my Rails apps. My first step is to fix the failing tests in my Rails 3 beta4 app.

My last 3 failing tests have to do with the devise gem and its authenticate_user! method in a before_filter at the top of my controller.

You'd earn great karma by helping me out with this since it will enable me to use the TDD methodology from now on.

Here is the error that troubles me:

1) Error:
test_should_get_accepted(ModerationControllerTest):
NoMethodError: undefined method `authenticate!' for nil:NilClass
    /test/functional/moderation_controller_test.rb:10:in `test_should_get_accepted'

Devise just gives functional tests pointers and helpers in this page: http://github.com/plataformatec/devise but I just don't know how to put this into application.

Can you please give this testing noob some detailed instructions on how to use these helpers?


回答1:


It took me a while but I found the way. Here it is for anyone stuck at the same point:

At the top of the moderation_controller_test.rb, below the class declaration, add this line:

include Devise::TestHelpers

I have 2 records in my user fixture and I added this line within each test where the user has to be authorized to perform the action.

sign_in User.first

Of course it's dead simple once you know how to do it.




回答2:


If you want the Devise test helpers to be available to all of your tests, you have to enclose the include mentioned by allesklar at the bottom of test_helper.rb in a class declaration like this:

class ActionController::TestCase
  include Devise::TestHelpers
end

Update: 01.25.2017

... rails 5 posts a DEPRECATION WARNING & asks you use ...

Devise::Test::ControllerHelpers




回答3:


I'm relatively new to Rails, so I'd like to add a couple things that may not be obvious to other new folks.

Concerning the user fixture, I had to define one but leave it empty in order for this to work:

# in users.yml    
joe: {}

When using the devise sign_in helper, you can access the hash object directly in your test:

# a test method in some_controller_test.rb
sign_in users(:joe)

See http://guides.rubyonrails.org/testing.html#the-low-down-on-fixtures for more information on Rails fixtures.




回答4:


Quoting verbatim from https://github.com/plataformatec/devise:

If you're using RSpec, you can put the following inside a file named spec/support/devise.rb:

RSpec.configure do |config|

config.include Devise::TestHelpers, :type => :controller

end

You can now use sign_in and sign_out in your RSpec tests.




回答5:


In addition to the code in the test_helpers.rb, I added this at the top of the controller_test and it worked for me:

require 'test_helper'


来源:https://stackoverflow.com/questions/3187287/making-functional-tests-in-rails-with-devise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!