2012-01-20 53 views
5

我試圖在has_many關聯上測試accep_nested_attributes_for上的{:_destroy =「1」}屬性。在Rails 3中使用RSpec在嵌套屬性上測試_destroy屬性

我得到它爲has_one協會工作,但我無法弄清楚如何做has_many。

尋找建議!謝謝^^本

 describe "nested attributes" do 

     describe "cell phone" do # the has_one association 
      it "accepts nested cell phone" do 
      contact = FactoryGirl.create(:contact) 
      contact.build_cell_phone(FactoryGirl.build(:cell_phone, :contact => contact).attributes) 
      lambda { 
       contact.save 
      }.should change(CellPhone, :count).by(1) 
      end 
      it "allows destroy attribute" do 
      contact = FactoryGirl.create(:contact) 
      cell_phone_attributes = FactoryGirl.build(:cell_phone, :contact => contact).attributes 
      contact.build_cell_phone(cell_phone_attributes) 
      contact.save 
      contact.cell_phone.should be_kind_of(CellPhone) 
      cell_phone_attributes.merge({:_destroy => "1"}) 
      lambda { 
       contact.cell_phone_attributes = cell_phone_attributes 
      }.should change(CellPhone, :count).from(1).to(0) 
      end 
      it "rejects a cell phone with a blank number" do 
      contact = FactoryGirl.create(:contact) 
      contact.build_cell_phone(FactoryGirl.build(:cell_phone, :contact => contact, :number => "").attributes) 
      lambda { 
       contact.save 
      }.should_not change(CellPhone, :count) 
      end 
      it "rejects a cell phone with a blank cell provider" do 
      contact = FactoryGirl.create(:contact) 
      contact.build_cell_phone(FactoryGirl.build(:cell_phone, :contact => contact, :cell_provider_id => "").attributes) 
      lambda { 
       contact.save 
      }.should_not change(CellPhone, :count) 
      end 
     end 

     describe "jobs" do # the has_many association 
      it "accepts nested jobs" do 
      contact = FactoryGirl.create(:contact) 
      contact.jobs_attributes = 3.times.collect { FactoryGirl.build(:job, :contact => contact).attributes } 
      lambda { 
       contact.save 
      }.should change(Job, :count).by(3) 
      end 
      xit "allows destroy attribute" do # TODO skipped test 
      contact = FactoryGirl.create(:contact) 
      jobs_attributes = 3.times.collect { FactoryGirl.build(:job, :contact => contact).attributes } 
      contact.jobs_attributes = jobs_attributes 
      contact.save 
      contact.jobs.count.should == 3 
      # these are the old jobs_attributes, there is no jobs_attributes getter method on Contact! 
      jobs_attributes = jobs_attributes.each.collect { |hash| hash.merge({:_destroy => "1"}) } 
      lambda { 
       # this doesn't work, the attributes are from before the jobs were created 
       contact.jobs_attributes = jobs_attributes 
       contact.save 
      }.should change(Job, :count).from(3).to(0) # this fails, Job.count == 3 after the test 
      end 
     end 
     end 

回答

0

你傳遞:allow_destroy => true選項accepts_nested_attributes_for

它應該看起來像:

class Contact 
    accepts_nested_attributes_for :jobs, :allow_destroy => true 
end