如何使用 Minitest 登录设计以测试控制器 [英] How to sign_in for Devise to Test Controller with Minitest

查看:11
本文介绍了如何使用 Minitest 登录设计以测试控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Rails 测试的新手.

I'm newbie to Rails Testing.

在学习了一些在线教程后,我可以为模型设置和运行测试.

After following some tutorial online, I could able to setup and run testing for Model.

但是当尝试测试 Controller 时,测试失败,因为它被重定向到登录页面.

But when trying to test for Controller, Testing was failed as it is redirected to login page.

我已经尝试了所有可以在网络上找到的用于登录设备的说明,但仍然无法登录并继续前进.

I've tried every instruction I can find on web to sign in for devise and still couldn't able to sign in and move forward.

感谢有人能提供帮助并为我指明前进的方向.

Appreciate if someone could help and give me a direction to move forward.

AwardedBidsControllerTest
  test_should_get_index                                           FAIL (0.45s)
MiniTest::Assertion:         Expected response to be a <:success>, but was <302>

以下是我的设置

Below is my setup

test/test_helper.rb

test/test_helper.rb

ENV["RAILS_ENV"] = "test"
require File.expand_path("../../config/environment", __FILE__)
require "rails/test_help"
require "minitest/rails"
require "minitest/reporters"
Minitest::Reporters.use!(
  Minitest::Reporters::SpecReporter.new,
  ENV,
  Minitest.backtrace_filter
)

class ActiveSupport::TestCase
  fixtures :all
  include FactoryGirl::Syntax::Methods
end

class ActionController::TestCase
  include Devise::TestHelpers
end

test/controllers/awarded_bids_controller_test.rb

test/controllers/awarded_bids_controller_test.rb

require "test_helper"

class AwardedBidsControllerTest < ActionController::TestCase
  test "should get index" do
    user = create(:user)
    sign_in user
    get :index
    assert_response :success
  end
end

app/controllers/awarded_bids_controller.rb

app/controllers/awarded_bids_controller.rb

class AwardedBidsController < ApplicationController
  before_filter :authenticate_user!

  def index
    @awarded_bids = AwardedBid.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @awarded_bids }
    end
  end
end

test/factories/users.rb

test/factories/users.rb

#using :login instead of :email.

FactoryGirl.define do
  factory :user do |u|
    u.login "user"
    u.name "Normal"
    u.surname "User"
    u.password "Abc2011"
  end
end

以下是版本信息,
JRuby 1.7.21(Ruby 1.9.3)
Rails 3.2.22
设计 3.0.4
迷你测试 4.7.5

Below is the version info.,
JRuby 1.7.21(Ruby 1.9.3)
Rails 3.2.22
Devise 3.0.4
Minitest 4.7.5

推荐答案

来自 integration_helpers.rb,例如:

class PostsTest < ActionDispatch::IntegrationTest
  include Devise::Test::IntegrationHelpers

  test 'authenticated users can see posts' do
    sign_in users(:bob)

    get '/posts'
    assert_response :success
  end
end

这篇关于如何使用 Minitest 登录设计以测试控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆