0

我有以下型號Rails3中+ rspec2 + factorygirl協會

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 "[email protected]" 
    end 
end 

#test/factories/users.rb 
FactoryGirl.define do 
factory :user do |u| 
    u.email '[email protected]' 
    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 

,但我發現這個錯誤,與守衛(即使重起後衛隊)

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. 

任何幫助將是感謝,提前致謝

回答

0

User您的User模型未聲明belongs_to關聯,因爲您的工廠假定它會:

你應該添加:

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上市啦)

+0

這個工作:)謝謝,愚蠢的我。我試着測試下一次LOL協會:),再次感謝 – sameera207

+0

順便說一句,對於你正在做的測試的孩子,你應該看看https://github.com/thoughtbot/shoulda。在其他很酷的功能中,它允許你寫'it {should validate_presence_of(:password)}' – pjam