friendly_id和rspec控制器测试,找到正确的id

时间:2014-10-08 14:16:48

标签: ruby-on-rails ruby rspec friendly-id

我有一个简单的rspec控制器测试基本的crud函数。我最近将Friendly_id添加到了我的控制器 - 现在所有的测试都失败了。

describe "PATCH update" do

      context "where the record is found" do 
        before do
          allow(model).to receive(:find).and_return(instance)
        end

        context "where the record is a root" do 
          before do 
            allow(instance).to receive(:root?).and_return(true)
          end

          context "where the record is updated" do
            before do
              allow(instance).to receive(:save).and_return(true)
              patch :update, instance.slug
            end

            it "should set a flash notice" do 
              flash[:notice].should_not be_nil
            end

            it "should redirect to panel page" do 
              response.should redirect_to(admin_corporate_pages_path)
            end
          end
        end
      end
    end  

所有这些都因以下错误而失败,

 1) Admin::CorporatePagesController for authenticated users GET edit returns http success
     Failure/Error: get :edit, id: corporate_page
     NoMethodError:
       undefined method `friendly' for #<Class:0x007f993a956b88>


  2) Admin::CorporatePagesController for authenticated users PATCH update where the record is found where the record is a root where the record is updated should set a flash notice
     Failure/Error: patch :update, instance.slug
     ActionController::UrlGenerationError:
       No route matches {:action=>"update", :controller=>"admin/corporate_pages"}

这是相关的控制器,

  def update
    if @corp_page
      @path = (@corp_page.root? ? admin_corporate_pages_path : admin_corporate_page_path(@corp_page.root))
      if @corp_page.update_attributes(params[:corporate_page]) 
        flash[:notice] = 'Page updated'
        redirect_to @path and return 
      else
        flash[:error]= 'There was an error'
        render :new and return
      end
    else
      flash[:error] = "Record not found"
    end
    redirect_to admin_corporate_pages_path
  end

  private
    def get_corp_page
      @corp_page = CorporatePage.friendly.find(params[:id])
    end  

我不知道如果友好ID使用:id函数,它会如何有所作为。怎么会对测试产生如此大的影响呢?

1 个答案:

答案 0 :(得分:4)

您需要解决两件事。首先,您的实例没有设置slug属性,导致错误为2.此外,您的调用似乎不正确,应该是:

patch :update, id: instance.to_param      # Let model decide which column it is to use

第二个错误是由:

引起的
allow(model).to receive(:find).and_return(instance)

将其更改为:

allow(model).to receive_message_chain(:friendly, :find).and_return(instance)