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

标签 ruby-on-rails ruby-on-rails-3 testing 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 => "foobar",
        :password_confirmation => "foobar" 
      }
    end

最佳答案

检查以确保 user_spec.rb 上没有 block 在 before(:each) 中调用 User.create 使用相同的电子邮件地址进行阻止。如果您的 block 嵌套不正确,您将收到此错误。例如,在 Rails 教程中,很容易不小心将 describe "admin attribute" 嵌套在 describe "password encryption" block 中,该 block 使用与之前相同的 (:each) 代码。

关于ruby-on-rails - 为什么我的 rspec 测试失败了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5131692/

相关文章:

jquery - 如何使用 jQuery 将电子邮件地址发送到 Rails 3.2 Controller ?

javascript - Bootstrap 下拉列表在我切换页面后停止工作 - Rails 4.2

ruby-on-rails - Devise、OmniAuth 和 Facebook - 如何让用户编辑密码?

ruby-on-rails - 在 I18n 消息中使用 a/an

ruby - 如何在 user_controller_spec 中以用户身份登录?

testing - golang 单元测试 : inner function parameters

java - Spring上下文编译时验证

testing - 协议(protocol)栈开发的嵌入式测试

ruby-on-rails-3 - ffmpeg使用carrierwave处理后如何将文件保存到s3

ruby-on-rails - 与 has_many :through association 的奇怪关联错误