2013-12-12 1 views
0

У меня есть приложение rails 3.2.16, у которого есть модель и контроллер для загрузки файла csv, который содержит список деталей клиента. В самом приложении это прекрасно работает, однако я не могу заставить тест работать.Загрузка файла RSpec вызывает «неопределенный метод» для строки заголовка

В основном я получаю сообщение об ошибке, что говорит

undefined method 'first_name,last_name,address_1,address_2,city .... etc.' 

Так он пытается использовать первую строку файла CSV как метод ...?

Файлов Я использую показаны ниже

спецификации (комментируемая из линии показывает то, что я пытался по дороге, увидев другие вопросы в SO)

it "upload a file with correct properties" do 
    #include Rack::Test::Methods 
    # @file = fixture_file_upload(Rails.root.join('spec/fixtures/files/cust-imp-good.csv'), 'text/csv') 
    @file = Rack::Test::UploadedFile.new(Rails.root.join('spec/fixtures/files/cust-imp-good.csv'), 'text/csv') 

    post :create, :customer_import => @file 
    response.should be_success 
end 

загрузчик модель

class CustomerImport #< ActiveRecord::Base 
    extend ActiveModel::Naming 
    include ActiveModel::Conversion 
    include ActiveModel::Validations 

    attr_accessor :file 

    def initialize(attributes = {}) 
    debugger 
    attributes.each { |name, value| send("#{name}=", value) } 
    end 

    def persisted? 
    false 
    end 

    def save 
    if imported_customers.map(&:valid?).all? 
     valid_ids = true 

     dive_shop_ids = DiveShop.ids_array 
     discount_level_ids = DiscountLevel.ids_array 

     imported_customers.each_with_index do |customer, index| 
     if !dive_shop_ids.include?(customer.dive_shop_id) 
      errors.add :base, "Row #{index+2}: dive_shop_id #{customer.dive_shop_id} is not valid" 
      valid_ids = false 
     end 
     if !discount_level_ids.include?(customer.discount_level_id) 
      errors.add :base, "Row #{index+2}: discount_level_id #{customer.discount_level_id} is not valid" 
      valid_ids = false 
     end   
     end 

     if valid_ids 
     imported_customers.each(&:save!) 
     return_val = imported_customers.count 
     else 
     false 
     end 

    else 
     imported_customers.each_with_index do |customer, index| 
     customer.errors.each do |message| 
      errors.add :base, "Row #{index+2}: #{message}" 
     end 
     end 
     false 
    end 

    end 

    def imported_customers 
    @imported_customers ||= ImportRecord.load_imported_records("Customer", file) 
    end 


end 

Из приведенной ниже ошибки я вижу, что она не работает в инициализаторе. Хотя, если я помещаю туда отладчик, инициализатор выглядит нормально.

Выход из отладчика внутри инициализаторе

rdb:1 attributes 
Rack::Test::UploadedFile:0x0000000b089a98 @content_type="text/csv", @original_filename="cust-imp-good.csv", @tempfile=#<File:/tmp/cust-imp-good.csv20131212-26548-ynutnh>> 
rdb:1 

Выход из сообщения RSpec отказа

Failures: 

    1) CustomerImportsController POST 'create' upload a file with correct properties 
    Failure/Error: post :create, :customer_import => @file 
    NoMethodError: 
     undefined method `first_name,last_name,address1,address2,address3,city,state,country,postcode,telephone,email,dob,local_contact,emergency_name,emergency_number,dive_shop_id,discount_level_id 
     =' for #<CustomerImport:0x0000000a5f7580> 
    # ./app/models/customer_import.rb:10:in `block in initialize' 
    # ./app/models/customer_import.rb:10:in `initialize' 
    # ./app/controllers/customer_imports_controller.rb:14:in `new' 
    # ./app/controllers/customer_imports_controller.rb:14:in `create' 
    # ./spec/controllers/customer_imports_controller_spec.rb:20:in `block (3 levels) in <top (required)>' 

любая помощь была бы оценена я попробовал решение, показанное на Undefined Method 'NameOfField' for #<Model:0x000...> т.е. граблей: дб: тест: подготовка и bundle exec rspec. но это не сработало ни

EDIT включить код контроллера

class CustomerImportsController < ApplicationController 
    before_filter do 
    @menu_group = "diveshop" 
    end 

    def new 
    @customer_import = CustomerImport.new 
    end 

    def create 

    if params[:customer_import] != nil 

     @customer_import = CustomerImport.new(params[:customer_import]) 
     return_value = @customer_import.save # need to add @customer_import.file here 
     if return_value != false  
     addauditlog("A bulk import of customers was carried out") 
     redirect_to customers_url, notice: "Imported #{return_value} customers successfully." 
     else 
     render :new 
     end 
    else 
     flash[:error] = "You have not selected a file" 
     redirect_to new_customer_import_url 
    end 
    end 

end 

ответ

0

При создании нового экземпляра модели, контроллер, похоже, принял хэш в качестве параметра с ключом, значение которого является первая строка файла csv. Вам нужно будет поделиться кодом контроллера и первой строкой обновленного файла, чтобы иметь возможность подтвердить это и предоставить дополнительную информацию.

+0

Добавили этот код. Первая строка файла точно такая же, как показывает ошибка. –

Смежные вопросы