2

我正在尝试使用 rspec + 制造进行简单的测试。不幸的是,没有太多像样的文章。

在 spec/model/event_spec.rb

require 'spec_helper'

describe Event do
  subject { Fabricate(:event) }

  describe "#full_name" do
    its(:city) { should == "LA" }
  end

end

在 spec/fabricators/event_fabricator.rb

Fabricator(:event) do
  user { Fabricate(:user) }

  # The test works if I uncomment this line:
  # user_id 1

  city "LA"
  description "Best event evar"
end

在 spec/fabricators/user_fabricator.rb

Fabricator(:user) do
  name 'Foobar'
  email { Faker::Internet.email }
end

我不断得到:

 1) Event#full_name city 
     Failure/Error: subject { Fabricate(:event) }
     ActiveRecord::RecordInvalid:
       Validation failed: User can't be blank

PS,如果有人知道任何在线文章/教程值得一读,开始使用 rspec 和制造。让我知道

4

1 回答 1

6

Fabricator 的特性之一是它会延迟生成关联,这意味着除非在模型上调用访问器,User否则不会生成关联。userEvent

看起来您的Event模型具有需要User存在的验证。如果是这种情况,您需要像这样声明您的制造商:

Fabricator(:event) do
  # This forces the association to be created
  user!
  city "LA"
  description "Best event evar"
end

这可确保User模型与 一起创建Event,这将允许您的验证通过。

见: http: //fabricationgem.org/# !defining-fabricators

于 2012-03-19T20:02:03.943 回答