context "can have 2 companies associated with it(v2)" do
it "should have an error when multiple companies can't belong to an industry " do
@company1 = Factory(:company)
@company2 = Factory(:company)
@industry = Factory(:industry)
@company1.industry = @industry
@company2.industry = @industry
@industry.should have(2).companies
end
end
这个测试失败了,我很难用它。 其他15项测试都可以。 问题是当我尝试使用相关对象时。
我的模特是:
class Company < ActiveRecord::Base
belongs_to :industry
validates_presence_of :name
validates_length_of :state, :is => 2, :allow_blank => true
validates_length_of :zip, :maximum => 30, :allow_blank => true
end
class Industry < ActiveRecord::Base
has_many :companies
validates_presence_of :name
validates_uniqueness_of :name
default_scope :order => "name asc"
end
只是插入记录本身似乎没问题 -
context "can have 2 companies associated with it" do
it "should have an error when multiple companies can't belong to an industry " do
lambda do
@company1 = Factory(:company)
@company2 = Factory(:company)
@industry = Factory(:industry)
@company1.industry = @industry
@company2.industry = @industry
end.should change(Company, :count).by(2)
end
end
btw我的规格的顶部是:
require 'spec_helper'
describe Industry do
before(:each) do
@industry = Factory(:industry)
end
我也注释掉了
# config.use_transactional_fixtures = true
位于spec/spec_helper.rb
的底部,但没有帮助
答案 0 :(得分:2)
如果公司属于一个行业,那么当你创建一家公司时,它就会为每个公司创造一个行业。
您可以通过将行业设置为公司来解决这个问题,但是您没有保存它们。或者,您可以:
before do
@industry = Factory(:industry)
@company1 = Factory(:company, :industry => @industry)
@company2 = Factory(:company, :industry => @industry)
end
it "should have both companies" do
@industry.companies.should == [@company1, @company2]
end