我试图在我的rails应用程序中测试一个destroy动作。我使用Factory_girl来创建对象。 创建公司对象时,必须添加用户关系。但是,当我尝试使用Factory_girl创建公司时,这就是我失败的地方。
user_spec.rb
describe User do
before(:each) { @user = User.new(email: 'user@example.com') }
subject { @user }
it { should respond_to(:email) }
it { should respond_to(:companies) }
it "#email returns a string" do
expect(@user.email).to match 'user@example.com'
end
describe "company associations" do
let!(:a_company) do
FactoryGirl.create(:company, user: @user)
end
it {should have_many :companies, :dependent => :destroy}
end
end
factory.rb
FactoryGirl.define do
factory :user do
confirmed_at Time.now
name "Test User"
email "test@example.com"
password "please123"
trait :admin do
role 'admin'
end
end
factory :company do
name "Total Inc."
user :user
end
end
模型/ user.rb
class User < ActiveRecord::Base
has_many :companies, dependent: :destroy
enum role: [:user, :vip, :admin]
after_initialize :set_default_role, :if => :new_record?
def set_default_role
self.role ||= :user
end
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :invitable, :database_authenticatable, :registerable, :confirmable,
:recoverable, :rememberable, :trackable, :validatable
end
模型/ company.rb
class Company < ActiveRecord::Base
belongs_to :user
validates :user_id, presence: true
end
我得到的错误:
故障:
1) User company associations
Failure/Error: FactoryGirl.create(:company, user: @user)
ActiveRecord::RecordInvalid:
Validation failed: User can't be blank
修改
我遵循了下面的建议,现在我可以创建但得到以下错误:
Failure/Error: it {should have_many :companies, :dependent => :destroy} expected #<User:0x007fc7b7ce08c0> to respond to has_many?
答案 0 :(得分:2)
第一个错误Validation failed: User can't be blank
是未保存@user
对象的结果。您可以在调用create:
let!(:a_company) do
@user.save
FactoryGirl.create(:company, user: @user)
end
第二个错误Failure/Error: it {should have_many :companies, :dependent => :destroy} expected #<User:0x007fc7b7ce08c0> to respond to has_many?
是一个测试错误 - 生产代码工作正常。要修复测试,请尝试以下选项之一:
使用Shoulda
it {should have_many(:companies).dependent(:destroy)}
使用FactoryGirl
it 'Expects user to have many companies' do
expect{@user.companies}.to_not raise_error
end