Easy Active Record Tutorial

时间:2016-01-19 10:42:29

标签: ruby-on-rails factory-bot

我在阅读教程时遇到了一个失败的测试:Jason Gilmore为Rails开发人员提供的简单活动记录。

对于某些上下文,本教程指示我生成位置模型。结果如下:

rails generate model Location name:string
  invoke  active_record
  create    db/migrate/20140724130112_create_locations.rb
  create    app/models/location.rb
  invoke    rspec
  create      spec/models/location_spec.rb
  invoke      factory_girl
  create       spec/factories/locations.rb

在" 使用FactoryGirl定义灯具"部分中,Gilmore想要展示FactoryGirl如何提供生成模型工厂的工具。为此,我被指示打开spec / factories / locations.rb并期望看到:

FactoryGirl.define do 
  factory :location do
    name "MyString"
  end
end

然后修改上面的文件看起来像这样:

FactoryGirl.define do

  factory :location do 
    name 'Pizza Works'
  end 
end 

然后我被告知保存文件,即locations.rb并返回位置规范(spec / models / location.rb )并添加以下测试:

it "can be created using a factory" do 
  location = FactoryGirl.build(:location) 
  expect(location).to eq('Pizza Works')
end

第一个问题是没有这样的文件,即(spec / models / location.rb )不存在。 spec文件夹中与该文件最接近的文件是(spec / models / location_spec.rb )。

因此猜测这是一个错字,我将上述测试添加到(spec / models / location_spec.rb )。

我的第一个问题是我错过了location.rb文件吗?或者这是吉尔摩尔的一个错字?

其次,使用

运行测试后
rspec -fd spec/models/location_spec.rb 

教程说我应该得到以下结果

Location
  can be instantiated
  has a valid factory
  can be assigned the name of an arcade

Finished in 0.04053 seconds (files took 2.05 seconds to load)
3 examples, 0 failures

但我得到的是

Location
  can be instantiated
  can be assigned the name of an arcade
  can be created using a factory (FAILED - 1)

Failures:

  1) Location can be created using a factory
     Failure/Error: expect(location).to eq('Pizza Works')

       expected: "Pizza Works"
            got: #<Location id: nil, created_at: nil, updated_at: nil, name: "Pizza Works", description: nil>

       (compared using ==)

       Diff:
       @@ -1,2 +1,7 @@
       -"Pizza Works"
       +#<Location:0x007fcf66060850
       + id: nil,
       + created_at: nil,
       + updated_at: nil,
       + name: "Pizza Works",
       + description: nil>

     # ./spec/models/location_spec.rb:18:in `block (2 levels) in <top (required)>'

Finished in 0.05663 seconds (files took 3.26 seconds to load)
3 examples, 1 failure

所以我的第二个问题是,为什么我的测试失败了,我应该怎么做才能修复它?

非常感谢任何帮助

2 个答案:

答案 0 :(得分:1)

这是规范中的错误。测试应该是

expect(location.name).to eq('Pizza Works')

答案 1 :(得分:1)

您希望位置名称为“Pizza Works”。不是对象'位置'自己。

更新此代码:

it "can be created using a factory" do 
  location = FactoryGirl.build(:location) 
  expect(location.name).to eq('Pizza Works')
end