【问题标题】:Rails rspec undefined method for #<RSpec::ExampleGroups#<RSpec::ExampleGroups 的 Rails rspec 未定义方法
【发布时间】:2016-04-27 14:07:43
【问题描述】:

我的 ApplicationController 中有 set_seo 方法

def set_seo(page)
   set_meta_tags :site => '', :title => page.seo_title ? page.seo_title : '', :reverse => true,
              :description => page.seo_description ? page.seo_description : ""
end

并想测试包含此方法的 BrandsController

 def index
    #some code here
    set_seo(@content)
 end

我的控制器规格

require 'spec_helper'

describe BrandsController do
  render_views
  before(:all) do
     @content = create(:content)
     create(:user)
  end

  describe "GET index" do
    it "index" do
      allow(ApplicationController).to receive(set_seo(@content)).and_return(set_seco(@content))
      brand = Brand.create
      get :index
      expect(response).to render_template(:index)
    end

但我有

 NoMethodError:
   undefined method `set_seo' for #<RSpec::ExampleGroups::BrandsController::GETIndex:0x007f866daa96c8>

【问题讨论】:

    标签: ruby-on-rails rspec controller


    【解决方案1】:

    set_seo 未在您的规范中定义,因此出现undefined method 错误。您必须将方法作为模拟/存根的符号传递(换句话说,您正在替换或“模拟”该方法的行为,而不是直接调用它)。

    也就是说,这条线有什么意义:allow(ApplicationController).to receive(set_seo(@content)).and_return(set_seco(@content))?不是告诉:set_seo返回它已经返回的吗?

    如果您要确保实际调用了 set_seo,请使用以下命令:

    expect_any_instance_of(ApplicationController).to receive(:set_seo).with(@content).and_call_original
    

    【讨论】:

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