0

我是 Rails 新手,我想用 rspec、should 和 factory girl 测试现有的 rails 项目。
我尝试为模型的变量赋值,但我不能。
这是错误;

Failure/Error: @brief.brand_info = 'bla bla bla'
  NoMethodError:
    undefined method `brand_info=' for nil:NilClass
  # ./spec/models/brief_spec.rb:34:in `block (3 levels) in <top (required)>'

您可以通过访问此链接访问我的模型和工厂...

简要工厂代码;

Factory.define :brief, :class => Brief do |b|
  b.brand_info 'brand info'
  b.duration 14
end

项目工厂代码;

Factory.define :project, :class => Project do |p|
  p.association :owner, :factory => :customer

  p.title 'project title'
  p.description 'project description'
  p.stage :brief_completed
  p.contest_type :standard

  p.brief {|p| p.association(:brief)}
  p.association :project_type, :factory => :project_type
end

Factory.define :project_with_prize, :parent => :project do |p|
  p.prize 5000
  p.stage :prize_determined
end

Factory.define :project_waiting_for_payment, :parent => :project_with_prize do |p|
  p.stage :awaiting_payment
end

Factory.define :project_started, :parent => :project_with_prize do |p|
  p.start Time.zone.now
  p.end Time.zone.now.advance(:days => 14)
  p.stage :started
end

Factory.define :project_started_with_no_brief, :parent => :project_with_prize do |p|
  p.brief nil
  p.start Time.zone.now.advance(:days => -10)
  p.end Time.zone.now.advance(:days => 4)
  p.stage :started
end

Factory.define :project_overdue, :parent => :project_with_prize do |p|
  p.start Time.zone.now.advance(:days => -14)
  p.end Time.zone.now.advance(:minutes => -15)
  p.stage :started
end

Factory.define :project_ended, :parent => :project_with_prize do |p|
  p.start Time.zone.now.advance(:days => -15)
  p.end Time.zone.now.advance(:days => -1)
  p.stage :ended
end

Factory.define :project_revising, :parent => :project_ended do |p|
  p.stage :revising
end

Factory.define :project_delivering_files, :parent => :project_ended do |p|
  p.stage :delivering_files
end

Factory.define :project_completed, :parent => :project_ended do |p|
  p.stage :completed
end


Factory.define :faulty_project, :parent => :project do |p|
  p.title nil
end
4

2 回答 2

2

失败消息包含一些线索:

  • undefined method 'brand_info=' for nil:NilClass表示该#brand_info=方法正在一个没有定义它的对象上被调用;在这种情况下,nil
  • Failure/Error: @brief.brand_info = 'bla bla bla'显示发生这种情况的代码行。出于某种原因@brief,您的规范中为零,但您尚未发布规范代码,所以我无法告诉您原因。

我建议从一个仅使用describe/的简单规范开始it(例如 no beforelet等),然后执行以下操作:

describe Brief do
  it 'assigns the brand info' do
    brief = Brief.new
    brief.brand_info = 'bla bla bla'
  end
end

一旦你得到了这个工作,你可以Brief.new用一个电话来代替工厂女孩(如果你真的需要工厂女孩提供的额外设置——但要知道这是额外的逻辑会减慢你的规范),你可以重构let一次您有多个需要对实例进行操作的brief示例。

于 2012-08-19T22:56:36.000 回答
0

感谢您的意见。我通过在 before 块中(而不是在 setup 块中)声明变量来解决这个问题。

于 2012-08-20T00:19:51.767 回答