【问题标题】:Unexpected test failure with RSpec and FactoryRSpec 和 Factory 的意外测试失败
【发布时间】:2012-05-30 12:52:39
【问题描述】:

RoR 控制器:

def destroy 
    Page.find(params[:id]).destroy 
    @pagechildren =  Page.where("parent_id = ?", params[:id]) 
    @pagechildren.update_all({parent_id: -1}) if @pagechildren.count > 
0 
    flash[:success] = 
t('activerecord.errors.controllers.message.attributes.page.page_destroy_suc cess') 
    redirect_to pages_path 
  end 

测试 RSpec

     it "should remove parent_id from children" do 
       @page2 = Factory(:page) 
       @pagechild = Factory(:page) 
       @pagechild[:parent_id] = @page2.id 
       lambda do 
          delete :destroy, :id => @page2 
        end.should 
change(@pagechild, :parent_id).from(@page2.id).to(-1) 
      end 

代码工作正常(),但是

Код все корректно обрабатывает(捕获 'id' 删除页面,对所有 孩子的 parent_id 更改为 -1)。但是 rspec 测试失败了。

工厂:

Factory.define :page do |page| 
  page.name "Name example page" 
  page.title "Title example page" 
  page.content "Content example page" 
  page.metadescription "metadescription example page" 
  page.metakeywords "metakeywords example page" 
  page.head "head example page" 
  page.ismenu true 
  page.order_id -1 
  page.parent_id -1 
end 

测试是红色的 =( 怎么了?

【问题讨论】:

  • rspec 测试说:parent_id 没有被 -1 改变
  • 请缩小断言失败的范围以及测试的代码是什么。
  • 控制器操作的代码过多,尝试将其移动到模型中,例如:Page.find(params[:id]).destroy_unsetting_children。顺便说一句,这是什么数据库需要将外键设置为-1 而不是NULL

标签: ruby-on-rails ruby rspec factory


【解决方案1】:

您的代码将更新数据库中的所有子项。但不是你的测试实例:) 试试这个:

it "should remove parent_id from children" do 
       @page2 = Factory.create(:page) 
       @pagechild = Factory.create(:page) 
       @pagechild[:parent_id] = @page2.id 
       delete :destroy, :id => @page2 
       @pagechild.reload.parent_id.should == -1
end

【讨论】:

    【解决方案2】:

    试试

    delete :destroy, :id => @page2.id
    

    如果仍然不起作用,则显示 rspec 输出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多