簡體   English   中英

rails3 + rspec2 + factorygirl協會

[英]rails3 + rspec2 + factorygirl association

我有以下型號

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
        :recoverable, :rememberable, :trackable, :validatable

     attr_accessible :email, :password, :password_confirmation, :remember_me, :company_id
end


 class Company < ActiveRecord::Base
   attr_accessible :email, :name
 end


#test/factories/companies.rb
FactoryGirl.define do
  factory :company do
    name "sample company"
    email "sample@company.com"
  end
end

#test/factories/users.rb
FactoryGirl.define do
 factory :user do |u|
   u.email 'sameera@sample.com'
   u.password 'welcome'
   u.password_confirmation 'welcome'
   u.association :company, :factory => :company
 end
end


#spec/models/user_spec.rb
require 'spec_helper'

describe User do
   describe "Validations" do
     it "should validate the email" do
       user = FactoryGirl.build(:user, :email => nil)
       user.should have(1).error_on(:email)
     end
   end
end

但是我在使用Guard時遇到了這個錯誤(即使在重新啟動Guard之后)

15:47:35 - INFO - Running: spec/models/user_spec.rb
Running tests with args ["--drb", "-f", "progress", "-r", "/home/sameera/.rvm/gems/ruby-1.9.2-p290/gems/guard-rspec-2.4.0/lib/guard/rspec/formatter.rb", "-f", "Guard::RSpec::Formatter", "--failure-exit-code", "2", "spec/models/user_spec.rb"]...
F

Failures:

  1) User Validations should validate the email
     Failure/Error: user = FactoryGirl.build(:user, :email => nil)
     NoMethodError:
       undefined method `company=' for #<User:0x00000004dcee08>
     # ./spec/models/user_spec.rb:6:in `block (3 levels) in <top (required)>'

Finished in 0.16308 seconds
1 example, 1 failure

Failed examples:

rspec ./spec/models/user_spec.rb:5 # User Validations should validate the email


Randomized with seed 26095

Done.

任何幫助,將不勝感激,在此先感謝

您的User模型未聲明出廠時的歸屬聲明關聯:

您應該添加它:

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
        :recoverable, :rememberable, :trackable, :validatable

     attr_accessible :email, :password, :password_confirmation, :remember_me, :company_id
  belongs_to :company
end

當然,這假定您的用戶表具有company_id列(但我想您已經添加了它,如在attr_accessible中列出的一樣)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM