How can I stub a controller helper method in a view spec with RSpec 3.4?

时光毁灭记忆、已成空白 提交于 2019-12-06 03:31:01
require 'rails_helper'

RSpec.describe 'account/articles/new', type: :view do

  it 'renders new article form' do
    stub_article { Article.new }
    render
    expect(rendered).to match(%r{form.+id="new_article".+action=\"#{account_articles_path}".+accept-charset=\"UTF-8\".+method=\"post\"})
  end

  def stub_article(&block)
    controller.singleton_class.class_exec(block) do
      helper_method :article
      define_method :article do
        block.call
      end
    end
  end

end

You can't stub article because

  • rspec-mocks' verify_partial_doubles configuration parameter is set to true, so RSpec only lets you stub and mock methods that an object implements, and
  • your controller doesn't actually implement article, so RSpec doesn't let you stub it.

You have two options:

  1. Disable verify_partial_doubles. This is a bad idea, because it will allow you to make mistakes in stubbing and mocking. Nonetheless, here's how to do it if you must: You probably have the following in your spec_helper.rb:

    RSpec.configure do |config|
      config.mock_with :rspec do |mocks|
        mocks.verify_partial_doubles = true
      end
    end
    

    Change it to verify_partial_doubles = false.

  2. Add the following manual 'stub' to your example:

    def view.article
      build(:article)
    end
    

    Or, if the view calls article more than once, build the article outside the method or just return it from the method.

There is a discussion of this situation in an rspec-rails Github issue.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!