【问题标题】:friendly_id and rspec controller tests, finding the correct idfriendly_id 和 rspec 控制器测试,找到正确的 id
【发布时间】:2014-10-08 14:16:48
【问题描述】:

我对基本的 crud 功能进行了简单的 rspec 控制器测试。我最近将 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 函数,我看不出它会有什么不同。它怎么会对测试产生如此大的影响?

【问题讨论】:

  • 您的测试中如何定义实例? friendly_id 是否在您的 Gemfile 中分组?
  • @BroiSatse 它适用于所有环境。我通过 let(:instance){FactoryGirl.create :corporate_page} 设置实例
  • 你们的工厂有没有一个料柱?

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


【解决方案1】:

您需要解决两件事。首先,您的实例没有设置 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)

【讨论】:

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