测试控制器与spec和工厂女孩,不能sign_in

时间:2012-08-26 00:32:48

标签: ruby-on-rails rspec devise factory-bot functional-testing

我是铁轨新手并测试铁路应用程序。我尝试使用rspec测试现有的rails应用程序。
我刚刚完成了模型测试,我也必须完成控制器测试。
但我在rspec上遇到sign_in方法的问题。我已经在互联网上尝试了所有的解决方法,但仍然无法像使用rspec的用户那样登录 这是我的控制器代码,它太简单了;

class AboutController < ApplicationController
  def index
  end

  def how_it_works
  end

  def what_is
  end

  def creative_tips
  end

  def brand_tips
  end

  def we_are
  end

  def faq
  end
end

这是我的规范代码;

require 'spec_helper'

describe AboutController do

  before(:all) do
    @customer=Factory.create(:customer)
    sign_in @customer
  end

  context 'index page :' do

    it 'should be loaded successfully' do
      response.should be_success
    end

  end

end

这是我的工厂代码;

Factory.define :unconfirmed_user, :class => User do |u|
  u.sequence(:user_name) {|n| "user_#{n}"}
  u.sequence(:email){|n| "user__#{n}@example.com"}
  u.sequence(:confirmation_token){|n| "confirm_#{n}"}
  u.sequence(:reset_password_token){|n| "password_#{n}"}
  u.password '123456'
  u.password_confirmation '123456'
  u.user_type :nil
end

Factory.define :user, :parent => :unconfirmed_user do |u|
  u.confirmed_at '1-1-2010'
  u.confirmation_sent_at '1-1-2010'
end

Factory.define :customer, :parent => :user do |u|
  u.user_type :customer
end

最后这是我的spec_helper代码

ENV["RAILS_ENV"] ||= 'test'
require File.dirname(__FILE__) + "/../config/environment" unless defined?(Rails)
require 'rspec/rails'
require "paperclip/matchers"

Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}

RSpec.configure do |config|
  config.include Paperclip::Shoulda::Matchers
end

RSpec.configure do |config|
  config.include Devise::TestHelpers, :type => :controller
end

RSpec.configure do |config|
  config.mock_with :rspec
  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.use_transactional_fixtures = true
end

gem文件;

gem 'rails', '3.0.3'
gem 'mysql2', '< 0.3'
.
.
.
gem "devise" , "1.1.5"
.
.
.

group :test do
  gem 'shoulda'
  gem "rspec-rails", "~> 2.11.0"
  gem "factory_girl_rails"
end

这是错误;

Failures:

  1) AboutController index page : should be loaded successfully
     Failure/Error: sign_in @customer
     NoMethodError:
       undefined method `env' for nil:NilClass
     # ./spec/controllers/about_controller_spec.rb:7:in `block (2 levels) in <top (required)>'

解决方案必须太简单,但我是新手,我无法找到它:(

2 个答案:

答案 0 :(得分:1)

您必须在it块内进行登录步骤才能使rspec能够访问响应,例如:

it 'should be loaded successfully' do
  sign_in @customer
  response.should be_success
end

答案 1 :(得分:1)

你没有主题。

require 'spec_helper'

describe AboutController do

  before(:all) do
    @customer=Factory.create(:customer)
    sign_in @customer
  end

  context 'index page :' do

    subject { Page }    
    it 'should be loaded successfully' do
      response.should be_success
    end

  end

end

您可能需要visit customers_path