ruby-on-rails – 为什么我的rspec测试失败了?

这是测试:

describe "admin attribute" do

        before(:each) do
          @user = User.create!(@attr)
        end

        it "should respond to admin" do
          @user.should respond_to(:admin)
        end

        it "should not be an admin by default" do
          @user.should_not be_admin
        end

        it "should be convertible to an admin" do
          @user.toggle!(:admin)
          @user.should be_admin
        end
      end

这是错误

1) User password encryption admin attribute should respond to admin
 Failure/Error: @user = User.create!(@attr)
 ActiveRecord::RecordInvalid:
   Validation Failed: Email has already been taken
 # ./spec/models/user_spec.rb:128

我认为错误可能在我的数据填充程序代码中的某处:

require 'faker'

namespace :db do
  desc "Fill database with sample data"
  task :populate => :environment do
    Rake::Task['db:reset'].invoke
    admin = User.create!(:name => "Example User",:email => "example@railstutorial.org",:password => "foobar",:password_confirmation => "foobar")
    admin.toggle!(:admin)             
    99.times do |n|
      name  = Faker::Name.name
      email = "example-#{n+1}@railstutorial.org"
      password  = "password"
      User.create!(:name => name,:email => email,:password => password,:password_confirmation => password)
    end
  end
end

如果我应该再复制我的代码,请告诉我.

更新:这是@attr定义的位置,位于user_spec.rb文件的顶部:

require 'spec_helper'

describe User do

  before(:each) do
      @attr = { 
        :name => "Example User",:email => "user@example.com",:password_confirmation => "foobar" 
      }
    end

解决方法

检查以确保在user_spec.rb中没有进一步阻止在具有相同电子邮件地址的before(:each)块中调用User.create.如果您的块嵌套不正确,您将收到此错误.例如,在Rails教程中,很容易意外地将描述的“admin属性”嵌套在描述的“密码加密”块中,该块使用相同的before(:each)代码.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...