ActiveRecord :: RecordInvalid:验证失败:已经采取了Sku

时间:2017-11-09 22:52:34

标签: ruby-on-rails unique factory-bot rspec-rails

您好我需要测试我的rspec请求,但是当我运行测试时显示此消息错误 我在我的模型和数据库中进行了验证,我实现了gem database-cleaner

的ActiveRecord :: RecordInvalid:        验证失败:Sku已被采取

这是我的模特产品

    FactoryGirl.define do

  #sequence(:sku) { Faker::Code.asin }

  factory :producto do
    name Faker::Name.name
    descripcion "MyText"
    resumen "Custom Resumen"
    precio_compra "9.99"
    precio_venta_inc_imp 9.99
    precio_venta_no_imp 9.45
    precio_supermercado 2.45
    porcentaje_ganancia 12
    categoria   # Cuando no se pone valor y es una relacion lo toma de una fabrica factory
    caracteristica 
    marca 
    impuesto

  end
end

这是我的请求测试,在此我创建两个记录但不起作用

require 'rails_helper'

RSpec.describe "Backend Productos", type: :request do
  #Inicializando test data
  #let!(:todos) { create_list(:producto, 2, sku: {Faker::Code.asin} ) }


  describe "GET #index" do
    context "cuando el usuario esta autenticado " do
      before do

         user1=FactoryGirl.create(:producto, sku: "AHDEC_1" )
         user2=FactoryGirl.create(:producto, sku: "455822" )
      end

      it "returns http success" do
        get "/backend/productos"
        expect(response).to have_http_status(:success)
      end
      it "retorna una lista de productos si hay datos" do

        expect(Producto.all.count).to eq(10)
      end  
    end

    context "cuando el usuario no esta autenticado" do
      it "Redirect to login form" do
      end  
    end

    context "cuando el usuario tiene perfil administrador" do
    end

    context "cuando el usuario NO tiene un perfil administrador" do
      it "muestra mensaje 'Acceso Prohibido'" do
        get "/backend/productos"
        expect(flash[:warning]).to have_content('Acceso Prohibido')
      end
      it "muestra codigo respuesta 401 - Not Authorized" do
        get 'backend/productos'
        expect(response.status).to eq 401
      end    
    end

  end
end

更新:

这是我的rails_helper with database-cleaner

# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
require 'support/factory_girl'
# Para limpiar la base de datos despues de cada prueba
require 'database_cleaner'

#
 Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }

# Checks for pending migration and applies them before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|
  # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
  config.fixture_path = "#{::Rails.root}/spec/fixtures"

  # If you're not using ActiveRecord, or you'd prefer not to run each of your
  # examples within a transaction, remove the following line or assign false
  # instead of true.
  config.use_transactional_fixtures = true

  # Add Config to Shoulda::Matcher
  Shoulda::Matchers.configure do |config|
    config.integrate do |with|
      # Choose a test framework:
      with.test_framework :rspec
      # Or, choose the following (which implies all of the above):
      with.library :rails
    end
  end

  # Configurar DataBase Cleaner to RSPEC
  config.before(:suite) do
    DatabaseCleaner.strategy = :transaction
    DatabaseCleaner.clean_with(:truncation)
  end



  config.around(:each) do |example|
    DatabaseCleaner.cleaning do
      example.run
    end
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end


  config.infer_spec_type_from_file_location!

  config.filter_rails_from_backtrace!


end

0 个答案:

没有答案