在rspec中flash [:notice] .should_not be_nil失败

时间:2011-12-09 22:42:44

标签: ruby-on-rails rspec

这是控制器的rspec代码:

it "should render edit if update was not saved" do
  item = Factory(:lease_item)
  session[:corp_head] = true
  post 'update', {:id => item.id, :name => 'nil'}
  flash[:notice].should_not be_nil
  response.should render 'edit'    
end

控制器中的更新是:

  def update
    if (eng? && dept_head?) || corp_head? || ceo?
      @lease_item = LeaseItem.find(params[:id])
      @lease_item.input_by_id = session[:user_id]
      if @lease_item.update_attributes(params[:lease_item], :as => :roles_update)

        #redirect
        redirect_to URI.escape("/view_handler?index=0&msg=Lease item updated successfully")
      else
        #back to new
        render 'edit', :notice => "Item NOT updated"
      end
    else
      #back to previous page
      redirect_to URI.escape("/view_handler?index=0&msg=NO right to update lease item")
    end    
  end

以下是rspec的错误代码:

  1) LeaseItemsController GET 'update' should render edit if update was not saved
     Failure/Error: flash[:notice].should_not be_nil
       expected: not nil
            got: nil
预计闪存中会出现“未更新的项目”。但是为什么flash [:notice]什么都没有?或者如何rspec有一条带渲染'edit'的消息,:notice => '项目未更新'

感谢。

更新

以下是控制器的变化:

      ...........
      else
        #back to new
        flash[:notice] = "Item NOT updated"
        render 'edit'
      end
      .........

这是传递的rspec代码:

   it "should render edit if update was not saved" do
      item = Factory(:lease_item)
      session[:corp_head] = true
      post 'update', {:id => item.id, :lease_item => {:name => 'nil'}}
      flash.should_not be_nil
      response.should render_template(:action=> "edit")  
    end

如果使用flash [:notice] .should_not be_nil(或.. flash.now [:notice] ...)则无效。错误是Got nil,与之前相同。另外,response.should渲染'edit'(或... render:action =>'edit')也没有传递。错误是NameError或NoMethodError。不知道为什么。

2 个答案:

答案 0 :(得分:5)

将您的其他内容更改为:

else
  #back to new
  flash[:notice] = "Item NOT updated"
  render 'edit'
end

答案 1 :(得分:0)

首先,我无法确定您在代码中设置flash的具体位置。

无论如何,请替换:

  post 'update', {:id => item.id, :name => 'nil'}

使用:

  post 'update', {:id => item.id, :lease_item => { :name => 'nil' } }