1

我是 Rails 和测试 Rails 应用程序的新手。我尝试使用 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 '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)>'

解决方案一定太简单了,但我是新手,我找不到它:(

4

2 回答 2

1

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

it 'should be loaded successfully' do
  sign_in @customer
  response.should be_success
end
于 2012-08-26T00:35:54.193 回答
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.

于 2012-08-26T01:14:46.043 回答