Ruby on Rails使用Devise身份validation进行function测试
我正在寻找一个解决奇怪问题的方法。 我有一个控制器,需要身份validation(使用设计gem)。 我添加了Devise TestHelpers,但我无法让它工作。
require 'test_helper' class KeysControllerTest 'testuser@demomailtest.com', :password => 'MyTestingPassword', :password_confirmation => 'MyTestingPassword' ) sign_in @user @key = keys(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:keys) end test "should get new" do get :new assert_response :success end test "should create key" do assert_difference('Key.count') do post :create, :key => @key.attributes end assert_redirected_to key_path(assigns(:key)) end test "should destroy key" do assert_difference('Key.count', -1) do delete :destroy, :id => @key.to_param end assert_redirected_to keys_path end
结束
我在“rake test”窗口中得到以下输出:
29) Failure: test_should_create_key(KeysControllerTest) [/test/functional/keys_controller_test.rb:29]: "Key.count" didn't change by 1. expected but was . 30) Failure: test_should_destroy_key(KeysControllerTest) [/test/functional/keys_controller_test.rb:37]: "Key.count" didn't change by -1. expected but was . 31) Failure: test_should_get_index(KeysControllerTest) [/test/functional/keys_controller_test.rb:19]: Expected response to be a , but was 32) Failure: test_should_get_new(KeysControllerTest) [/test/functional/keys_controller_test.rb:25]: Expected response to be a , but was
有人可以告诉我,为什么设计不认证? 我正在使用与AdminController完全相同的过程,它完美无缺。
你使用Devise与确认? 在这种情况下,创建是不够的,您需要使用@user.confirm!
确认用户@user.confirm!
其次,为什么要在function测试中创建用户? 像这样在夹具中声明您的用户(如果您只需要确认,则为confirmed_at):
测试/装置/ users.yml里:
user1: id: 1 email: user1@test.eu encrypted_password: abcdef1 password_salt: efvfvffdv confirmed_at: <%= Time.now %>
并在您的function测试中签名:
sign_in users(:user1)
编辑:我刚看到,在我的应用程序中,Devise-Testhelpers在test / test-helpers.rb中声明,我不知道这是否有所作为,也许你想尝试:
ENV["RAILS_ENV"] = "test" require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' class ActionController::TestCase include Devise::TestHelpers end class ActiveSupport::TestCase # Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order. # # Note: You'll currently still have to declare fixtures explicitly in integration tests # -- they do not yet inherit this setting fixtures :all # Add more helper methods to be used by all tests here... end
这花了我一些时间来弄清楚但事实certificate答案非常简单。
关键是,在您的灯具文件(users.yml)中,您需要确保用户已“确认”(假设您在用户模型中指定了“确认”)。 所以,举个例子,把它放在你的users.yml中:
user_one: confirmed_at:2015/01/01
这就是全部,无需指定其他字段(电子邮件,加密密码等)。
现在在您的控制器测试中(例如在’setup’或’before’中),您只需编写代码:
sign_in users(:user_one)
然后它应该工作!
我有一个类似的问题(但使用FactoryGirl,而不是Fixtures)并且能够通过简单地使用FactoryGirl.create(:user)
而不是FactoryGirl.build(:user)
来解决它。
显然,Devise要求用户持久保存到数据库,以便一切正常工作。