加入模型创建测试失败,因为它缺少相关模型,不知道为什么?

时间:2011-10-18 02:38:49

标签: ruby-on-rails rspec

这是失败的测试:

before(:each) do
    @attr = { 
      :user_id => "1", 
      :project_id => "1",
      :owner_type => "client"
    }
  end

  it "should create a new instance given valid attributes" do
     Ownership.create!(@attr)
   end

这是失败:

Failures:

  1) Ownership should create a new instance given valid attributes
     Failure/Error: Ownership.create!(@attr)
     ActiveRecord::RecordInvalid:
       Validation failed: User can't be blank, Project can't be blank
     # ./spec/models/ownership_spec.rb:14:in `block (2 levels) in <top (required)>'

我没有对用户或项目进行任何验证而不是空白。这是我的所有权模式:

class Ownership < ActiveRecord::Base
  attr_accessible :owner_type

  belongs_to :project
  belongs_to :user

  validates :user_id, :presence => true

  validates :project_id, :presence => true

  validates :owner_type, :presence => true

end

我错过了什么吗?我做错了什么?此外,所有权都没有在实际的应用程序中创建..这是我正在使用但不起作用:

current_user.ownerships.create(:owner_type => 'designer', :project => @project)

这是我的用户模型:

class User < ActiveRecord::Base
  attr_accessible :name, :email, :admin, :projects

  has_many :ownerships
  has_many :projects, :through => :ownerships

  accepts_nested_attributes_for :projects

2 个答案:

答案 0 :(得分:0)

是否可能导致问题,因为您为user_idproject_id的值传递字符串而不是整数?

答案 1 :(得分:0)

:user_id:project_id添加到attr_accesible。就像你为:owner_type做的那样。所以看起来应该是

attr_accessible :owner_type, :user_id, :project_id

这应该可以解决问题。