2011-10-21 68 views
1
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個測試都可以。 問題是,當我嘗試使用相關的對象。rspec - 如何獲得測試通過

我的車型有:

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 

只需插入記錄本身似乎就ok了工作 -

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 

順便說一句我的規格的頂部是:

require 'spec_helper' 
describe Industry do 
    before(:each) do 
    @industry = Factory(:industry) 
    end 

我有也已註釋掉

# config.use_transactional_fixtures = true 

spec/spec_helper.rb底部,但沒有幫助

+0

您是否在嘗試調用與工業相關的公司之前調用reload? @ industry.reload –

+2

我認爲你需要在添加行業 –

回答

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 
+1

真棒後保存公司對象。順便說一句我也可以在最後使用'@industry.companies.count.should == 2' –