dimanche 23 août 2015

How to sign_in for Devise to Test Controller with Minitest

I'm newbie to Rails Testing.

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

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

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

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

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

#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

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

Aucun commentaire:

Enregistrer un commentaire