【问题标题】:Why do my Rspec tests fail after Rails 4 upgrade?为什么我的 Rspec 测试在 Rails 4 升级后失败?
【发布时间】:2013-12-04 12:39:32
【问题描述】:

我最近将我的 Rails 应用程序升级到 Rails 4,在我的 Rspec 测试套件中,一行代码导致错误:

ActiveRecord::StatementInvalid:
   TypeError: can't cast Array to string: INSERT INTO "items" ("created_at", "date", "description", "invoice_id", "position", "price_in_cents", "quantity", "tax_rate", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)

这是我的代码:

# /spec/controllers/invoices_controller_spec.rb:

require 'spec_helper'

describe InvoicesController do

  before :each do
    ...
    @invoice = FactoryGirl.create(:invoice, :project_id => @project.id, :user => @user, :items_attributes => [ FactoryGirl.attributes_for(:item) ]) # causing havoc
  end

  ...

end

# /spec/factories.rb:

factory :invoice do
  number 123
  recipient { Faker::Name.name }
  date { Time.zone.now.to_date }
  association :user
  association :project
  factory :invoice_with_item do
    items { |i| [i.association(:item)] }
  end
end

谁能告诉我这里缺少什么?

我猜这与Invoice 类接受嵌套项这一事实有某种关系。

【问题讨论】:

  • 我们知道问题的实质是什么吗? “造成严重破坏”的描述性不是很好。
  • 你为什么不使用 invoice_with_items? invoice = FactoryGirl.create(:invoice_with_items, :project_id => project.id, :user => user)?无论如何,正如 Sevenseacat 所说,“造成严重破坏”对任何人都没有帮助
  • @sevenseacat:好的,添加了上面的错误信息。
  • 可能是因为 item_attributes 应该是一个散列,而不是一个数组。就像从表单提交时一样。没有完整的错误,很难说。
  • @sevenseacat:不,它应该是一个数组。它在 Rails 3 中的工作方式类似,将其更改为哈希会在此处引发语法错误。

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


【解决方案1】:

您的问题可能与 Faker Gem 有关,尽管我认为它不会查看您的代码。我不确定 rails4 发生了什么变化会导致 Faker(或 factory_girl 出现问题)

我有一个这样的工厂:

FactoryGirl.define do
  factory :job, :class => Job do
    ...
    password        { Faker::Lorem.words()[0..38] }
    ...
  end
end

这导致了同样的错误(仅在 rails 4 - 在 3 中工作正常),直到我将其更改为 "Faker::Lorem.words().join()[0..38].to_s"

【讨论】:

  • 感谢这篇文章我不知道它会返回一个数组。这对我帮助很大。
  • 哦,谢谢! password 属性需要一个字符串,但是 words 方法返回一个数组。因此,如果将其转换为字符串,一切都会好起来的。
猜你喜欢
  • 2014-08-12
  • 1970-01-01
  • 1970-01-01
  • 2016-10-05
  • 2013-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多