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

孤者浪人 提交于 2019-12-07 17:52:13

问题


I'm testing a view with RSpec (3.4 on Rails 4.2.5). And I use the decent_exposure gem in my CRUD controller. decent_exposure makes it easy to define named methods that are made available to my views and which memoize the resultant values.

But I don't understand how I can stub these methods in a view spec. I tried do it according to the RSpec documentation, but it raises an error.

Why doesn't it work? How can I stub the method article in the view?

My controller

class Account::ArticlesController < Account::BaseController
  expose(:articles) { current_user.articles }
  expose(:article, attributes: :article_params)

  # POST /account/articles
  # POST /account/articles.json
  def create
    respond_to do |format|
      if article.save
        format.html { redirect_to account_article_url(article), notice: 'Article was successfully created.' }
        format.json { render :show, status: :created, location: account_article_url(article) }
      else
        format.html { render :new }
        format.json { render json: article.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /account/articles/1
  # PATCH/PUT /account/articles/1.json
  def update
    respond_to do |format|
      if article.update(article_params)
        format.html { redirect_to account_article_url(article), notice: 'Article was successfully updated.' }
        format.json { render :show, status: :ok, location: account_article_url(article) }
      else
        format.html { render :edit }
        format.json { render json: article.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /account/articles/1
  # DELETE /account/articles/1.json
  def destroy
    respond_to do |format|
      if article.destroy
        format.html { redirect_to account_articles_url, notice: 'Article was successfully destroyed.' }
        format.json { head :no_content }
      else
        format.html { redirect_to account_articles_url, notice: 'Article was not destroyed.' }
        format.json { render json: article.errors, status: :unprocessable_entity }
      end
    end
  end

  private

  def article_params
    params.require(:article).permit(:title, :announce, :content, :is_published, :published_at)
  end

end

And I have a view spec

require 'rails_helper'

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

  before do
    allow(view).to receive(:article).and_return(build(:article))
  end

  it 'renders new article form' do
    render
    expect(rendered).to match %Q{form[action=#{account_articles_path}][method=post]}
  end
end

But it raises an error

Failures:

  1) account/articles/new renders new article form
     Failure/Error: allow(view).to receive(:article).and_return(build(:article))
       #<#<Class:0x007fe85c2c7620>:0x007fe85d161208 @_routes=nil, @_config={}, @view_renderer=#<ActionView::Renderer:0x007fe85d1613c0 @lookup_context=#<ActionView::LookupContext:0x007fe85d1615a0 @details_key=nil, @details={:locale=>[:en], :formats=>[:html, :text, :js, :css, :ics, :csv, :vcf, :png, :jpeg, :gif, :bmp, :tiff, :mpeg, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :pdf, :zip], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder, :haml]}, @skip_default_locale=false, @cache=true, @prefixes=["", "account/articles"], @rendered_format=nil, @view_paths=#<ActionView::PathSet:0x007fe85d1614d8 @paths=[#<ActionView::OptimizedFileSystemResolver:0x007fe85d37fb48 @pattern=":prefix/:action{.:locale,}{.:formats,}{+:variants,}{.:handlers,}", @cache=#<ActionView::Resolver::Cache:0x007fe85d37fb20 @data=#<ActionView::Resolver::Cache::SmallCache:0x007fe85d37faf8 @backend={}, @default_proc=#<Proc:0x007fe85f071198@/Users/et/.rvm/gems/ruby-2.2.2/gems/actionview-4.2.5/lib/action_view/template/resolver.rb:49 (lambda)>>>, @path="/Users/et/Documents/projects/test-blog/app/views">, #<ActionView::OptimizedFileSystemResolver:0x007fe85d37feb8 @pattern=":prefix/:action{.:locale,}{.:formats,}{+:variants,}{.:handlers,}", @cache=#<ActionView::Resolver::Cache:0x007fe85d37fe90 @data=#<ActionView::Resolver::Cache::SmallCache:0x007fe85d37fe68 @backend={}, @default_proc=#<Proc:0x007fe85f071198@/Users/et/.rvm/gems/ruby-2.2.2/gems/actionview-4.2.5/lib/action_view/template/resolver.rb:49 (lambda)>>>, @path="/Users/et/.rvm/gems/ruby-2.2.2/gems/devise-3.5.3/app/views">]>>>, @request=#<ActionController::TestRequest:0x007fe85c35e048 @env={"rack.version"=>[1, 3], "rack.input"=>#<StringIO:0x007fe85f87eca0>, "rack.errors"=>#<StringIO:0x007fe85f87ed40>, "rack.multithread"=>true, "rack.multiprocess"=>true, "rack.run_once"=>false, "REQUEST_METHOD"=>"GET", "SERVER_NAME"=>"example.org", "SERVER_PORT"=>"80", "QUERY_STRING"=>"", "rack.url_scheme"=>"http", "HTTPS"=>"off", "SCRIPT_NAME"=>"", "CONTENT_LENGTH"=>"0", "HTTP_HOST"=>"test.host", "REMOTE_ADDR"=>"0.0.0.0", "HTTP_USER_AGENT"=>"Rails Testing", "action_dispatch.routes"=>#<ActionDispatch::Routing::RouteSet:0x007fe85c6713e8>, "action_dispatch.parameter_filter"=>[:password], "action_dispatch.redirect_filter"=>[], "action_dispatch.secret_token"=>nil, "action_dispatch.secret_key_base"=>"eb526d7f4b0c06b367225a0d32ba8b3c3287ea6d6de798961e6fe33b975d44c2cd3ae9f314f0b96c73029f052d4670bc5a4db850ffc6a73586043089f57bdb3b", "action_dispatch.show_exceptions"=>false, "action_dispatch.show_detailed_exceptions"=>true, "action_dispatch.logger"=>#<ActiveSupport::Logger:0x007fe85d32d528 @progname=nil, @level=0, @default_formatter=#<Logger::Formatter:0x007fe85d32d4b0 @datetime_format=nil>, @formatter=#<ActiveSupport::Logger::SimpleFormatter:0x007fe85d2fc928 @datetime_format=nil>, @logdev=#<Logger::LogDevice:0x007fe85d32d460 @shift_size=nil, @shift_age=nil, @filename=nil, @dev=#<File:/Users/et/Documents/projects/test-blog/log/test.log>, @mutex=#<Logger::LogDevice::LogDeviceMutex:0x007fe85d32d438 @mon_owner=nil, @mon_count=0, @mon_mutex=#<Mutex:0x007fe85d32d3e8>>>>, "action_dispatch.backtrace_cleaner"=>#<Rails::BacktraceCleaner:0x007fe85c2f4aa8 @filters=[#<Proc:0x007fe85c2f4878@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:14>, #<Proc:0x007fe85c2f4850@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:15>, #<Proc:0x007fe85c2f47d8@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:16>, #<Proc:0x007fe85c2f5750@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:29>], @silencers=[#<Proc:0x007fe85c2f59a8@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:19>], @root="/Users/et/Documents/projects/test-blog/">, "action_dispatch.key_generator"=>#<ActiveSupport::CachingKeyGenerator:0x007fe85f4cc580 @key_generator=#<ActiveSupport::KeyGenerator:0x007fe85f4cc5a8 @secret="eb526d7f4b0c06b367225a0d32ba8b3c3287ea6d6de798961e6fe33b975d44c2cd3ae9f314f0b96c73029f052d4670bc5a4db850ffc6a73586043089f57bdb3b", @iterations=1000>, @cache_keys=#<ThreadSafe::Cache:0x007fe85f4cc558 @backend={"signed_global_ids64"=>"0\xF4/#*5\xF2\x0F\xB2\x101\v~\xC5\x89\xFF\xDB\x11\xCB(U\xFA\xF87\x13Evz:\xAD\xD6\xA3r\x96\x9A\x82\x17\x84\tR\xF2A\xADV\x85u?^N\xBCT\x84\x10\x11\xD9\xC9>n\xA1\f\x06\xAAuU"}, @default_proc=nil>>, "action_dispatch.http_auth_salt"=>"http authentication", "action_dispatch.signed_cookie_salt"=>"signed cookie", "action_dispatch.encrypted_cookie_salt"=>"encrypted cookie", "action_dispatch.encrypted_signed_cookie_salt"=>"signed encrypted cookie", "action_dispatch.cookies_serializer"=>:json, "action_dispatch.cookies_digest"=>nil, "rack.session"=>{}, "rack.session.options"=>{:key=>"rack.session", :path=>"/", :domain=>nil, :expire_after=>nil, :secure=>false, :httponly=>true, :defer=>false, :renew=>false, :sidbits=>128, :cookie_only=>true, :secure_random=>SecureRandom, :id=>"8a8b5f8906289bb00109022394af0832"}, "action_dispatch.request.path_parameters"=>{:controller=>"account/articles", :action=>"new"}}, @filtered_parameters=nil, @filtered_env=nil, @filtered_path=nil, @protocol=nil, @port=nil, @method=nil, @request_method=nil, @remote_ip=nil, @original_fullpath=nil, @fullpath=nil, @ip=nil, @uuid=nil>, @response=#<ActionController::TestResponse:0x007fe85c2cf0a0 @mon_owner=nil, @mon_count=0, @mon_mutex=#<Mutex:0x007fe85c2cef38>, @stream=#<ActionDispatch::Response::Buffer:0x007fe85c2cedd0 @response=#<ActionController::TestResponse:0x007fe85c2cf0a0 ...>, @buf=[], @closed=false>, @header={"X-Frame-Options"=>"SAMEORIGIN", "X-XSS-Protection"=>"1; mode=block", "X-Content-Type-Options"=>"nosniff"}, @status=200, @sending_file=false, @blank=false, @cv=#<MonitorMixin::ConditionVariable:0x007fe85c2ced58 @monitor=#<ActionController::TestResponse:0x007fe85c2cf0a0 ...>, @cond=#<Thread::ConditionVariable:0x007fe85c2ced30>>, @committed=false, @sending=false, @sent=false, @content_type=nil, @charset=nil, @cache_control={}, @etag=nil>, @params={}, @_assigns={"request"=>#<ActionController::TestRequest:0x007fe85c35e048 @env={"rack.version"=>[1, 3], "rack.input"=>#<StringIO:0x007fe85f87eca0>, "rack.errors"=>#<StringIO:0x007fe85f87ed40>, "rack.multithread"=>true, "rack.multiprocess"=>true, "rack.run_once"=>false, "REQUEST_METHOD"=>"GET", "SERVER_NAME"=>"example.org", "SERVER_PORT"=>"80", "QUERY_STRING"=>"", "rack.url_scheme"=>"http", "HTTPS"=>"off", "SCRIPT_NAME"=>"", "CONTENT_LENGTH"=>"0", "HTTP_HOST"=>"test.host", "REMOTE_ADDR"=>"0.0.0.0", "HTTP_USER_AGENT"=>"Rails Testing", "action_dispatch.routes"=>#<ActionDispatch::Routing::RouteSet:0x007fe85c6713e8>, "action_dispatch.parameter_filter"=>[:password], "action_dispatch.redirect_filter"=>[], "action_dispatch.secret_token"=>nil, "action_dispatch.secret_key_base"=>"eb526d7f4b0c06b367225a0d32ba8b3c3287ea6d6de798961e6fe33b975d44c2cd3ae9f314f0b96c73029f052d4670bc5a4db850ffc6a73586043089f57bdb3b", "action_dispatch.show_exceptions"=>false, "action_dispatch.show_detailed_exceptions"=>true, "action_dispatch.logger"=>#<ActiveSupport::Logger:0x007fe85d32d528 @progname=nil, @level=0, @default_formatter=#<Logger::Formatter:0x007fe85d32d4b0 @datetime_format=nil>, @formatter=#<ActiveSupport::Logger::SimpleFormatter:0x007fe85d2fc928 @datetime_format=nil>, @logdev=#<Logger::LogDevice:0x007fe85d32d460 @shift_size=nil, @shift_age=nil, @filename=nil, @dev=#<File:/Users/et/Documents/projects/test-blog/log/test.log>, @mutex=#<Logger::LogDevice::LogDeviceMutex:0x007fe85d32d438 @mon_owner=nil, @mon_count=0, @mon_mutex=#<Mutex:0x007fe85d32d3e8>>>>, "action_dispatch.backtrace_cleaner"=>#<Rails::BacktraceCleaner:0x007fe85c2f4aa8 @filters=[#<Proc:0x007fe85c2f4878@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:14>, #<Proc:0x007fe85c2f4850@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:15>, #<Proc:0x007fe85c2f47d8@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:16>, #<Proc:0x007fe85c2f5750@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:29>], @silencers=[#<Proc:0x007fe85c2f59a8@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:19>], @root="/Users/et/Documents/projects/test-blog/">, "action_dispatch.key_generator"=>#<ActiveSupport::CachingKeyGenerator:0x007fe85f4cc580 @key_generator=#<ActiveSupport::KeyGenerator:0x007fe85f4cc5a8 @secret="eb526d7f4b0c06b367225a0d32ba8b3c3287ea6d6de798961e6fe33b975d44c2cd3ae9f314f0b96c73029f052d4670bc5a4db850ffc6a73586043089f57bdb3b", @iterations=1000>, @cache_keys=#<ThreadSafe::Cache:0x007fe85f4cc558 @backend={"signed_global_ids64"=>"0\xF4/#*5\xF2\x0F\xB2\x101\v~\xC5\x89\xFF\xDB\x11\xCB(U\xFA\xF87\x13Evz:\xAD\xD6\xA3r\x96\x9A\x82\x17\x84\tR\xF2A\xADV\x85u?^N\xBCT\x84\x10\x11\xD9\xC9>n\xA1\f\x06\xAAuU"}, @default_proc=nil>>, "action_dispatch.http_auth_salt"=>"http authentication", "action_dispatch.signed_cookie_salt"=>"signed cookie", "action_dispatch.encrypted_cookie_salt"=>"encrypted cookie", "action_dispatch.encrypted_signed_cookie_salt"=>"signed encrypted cookie", "action_dispatch.cookies_serializer"=>:json, "action_dispatch.cookies_digest"=>nil, "rack.session"=>{}, "rack.session.options"=>{:key=>"rack.session", :path=>"/", :domain=>nil, :expire_after=>nil, :secure=>false, :httponly=>true, :defer=>false, :renew=>false, :sidbits=>128, :cookie_only=>true, :secure_random=>SecureRandom, :id=>"8a8b5f8906289bb00109022394af0832"}, "action_dispatch.request.path_parameters"=>{:controller=>"account/articles", :action=>"new"}}, @filtered_parameters=nil, @filtered_env=nil, @filtered_path=nil, @protocol=nil, @port=nil, @method=nil, @request_method=nil, @remote_ip=nil, @original_fullpath=nil, @fullpath=nil, @ip=nil, @uuid=nil>, "response"=>#<ActionController::TestResponse:0x007fe85c2cf0a0 @mon_owner=nil, @mon_count=0, @mon_mutex=#<Mutex:0x007fe85c2cef38>, @stream=#<ActionDispatch::Response::Buffer:0x007fe85c2cedd0 @response=#<ActionController::TestResponse:0x007fe85c2cf0a0 ...>, @buf=[], @closed=false>, @header={"X-Frame-Options"=>"SAMEORIGIN", "X-XSS-Protection"=>"1; mode=block", "X-Content-Type-Options"=>"nosniff"}, @status=200, @sending_file=false, @blank=false, @cv=#<MonitorMixin::ConditionVariable:0x007fe85c2ced58 @monitor=#<ActionController::TestResponse:0x007fe85c2cf0a0 ...>, @cond=#<Thread::ConditionVariable:0x007fe85c2ced30>>, @committed=false, @sending=false, @sent=false, @content_type=nil, @charset=nil, @cache_control={}, @etag=nil>, "params"=>{}}, @_controller=#<ActionView::TestCase::TestController:0x007fe85c35e200 @_action_has_layout=true, @_routes=nil, @_headers={"Content-Type"=>"text/html"}, @_status=200, @_request=nil, @_response=nil, @request=#<ActionController::TestRequest:0x007fe85c35e048 @env={"rack.version"=>[1, 3], "rack.input"=>#<StringIO:0x007fe85f87eca0>, "rack.errors"=>#<StringIO:0x007fe85f87ed40>, "rack.multithread"=>true, "rack.multiprocess"=>true, "rack.run_once"=>false, "REQUEST_METHOD"=>"GET", "SERVER_NAME"=>"example.org", "SERVER_PORT"=>"80", "QUERY_STRING"=>"", "rack.url_scheme"=>"http", "HTTPS"=>"off", "SCRIPT_NAME"=>"", "CONTENT_LENGTH"=>"0", "HTTP_HOST"=>"test.host", "REMOTE_ADDR"=>"0.0.0.0", "HTTP_USER_AGENT"=>"Rails Testing", "action_dispatch.routes"=>#<ActionDispatch::Routing::RouteSet:0x007fe85c6713e8>, "action_dispatch.parameter_filter"=>[:password], "action_dispatch.redirect_filter"=>[], "action_dispatch.secret_token"=>nil, "action_dispatch.secret_key_base"=>"eb526d7f4b0c06b367225a0d32ba8b3c3287ea6d6de798961e6fe33b975d44c2cd3ae9f314f0b96c73029f052d4670bc5a4db850ffc6a73586043089f57bdb3b", "action_dispatch.show_exceptions"=>false, "action_dispatch.show_detailed_exceptions"=>true, "action_dispatch.logger"=>#<ActiveSupport::Logger:0x007fe85d32d528 @progname=nil, @level=0, @default_formatter=#<Logger::Formatter:0x007fe85d32d4b0 @datetime_format=nil>, @formatter=#<ActiveSupport::Logger::SimpleFormatter:0x007fe85d2fc928 @datetime_format=nil>, @logdev=#<Logger::LogDevice:0x007fe85d32d460 @shift_size=nil, @shift_age=nil, @filename=nil, @dev=#<File:/Users/et/Documents/projects/test-blog/log/test.log>, @mutex=#<Logger::LogDevice::LogDeviceMutex:0x007fe85d32d438 @mon_owner=nil, @mon_count=0, @mon_mutex=#<Mutex:0x007fe85d32d3e8>>>>, "action_dispatch.backtrace_cleaner"=>#<Rails::BacktraceCleaner:0x007fe85c2f4aa8 @filters=[#<Proc:0x007fe85c2f4878@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:14>, #<Proc:0x007fe85c2f4850@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:15>, #<Proc:0x007fe85c2f47d8@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:16>, #<Proc:0x007fe85c2f5750@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:29>], @silencers=[#<Proc:0x007fe85c2f59a8@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:19>], @root="/Users/et/Documents/projects/test-blog/">, "action_dispatch.key_generator"=>#<ActiveSupport::CachingKeyGenerator:0x007fe85f4cc580 @key_generator=#<ActiveSupport::KeyGenerator:0x007fe85f4cc5a8 @secret="eb526d7f4b0c06b367225a0d32ba8b3c3287ea6d6de798961e6fe33b975d44c2cd3ae9f314f0b96c73029f052d4670bc5a4db850ffc6a73586043089f57bdb3b", @iterations=1000>, @cache_keys=#<ThreadSafe::Cache:0x007fe85f4cc558 @backend={"signed_global_ids64"=>"0\xF4/#*5\xF2\x0F\xB2\x101\v~\xC5\x89\xFF\xDB\x11\xCB(U\xFA\xF87\x13Evz:\xAD\xD6\xA3r\x96\x9A\x82\x17\x84\tR\xF2A\xADV\x85u?^N\xBCT\x84\x10\x11\xD9\xC9>n\xA1\f\x06\xAAuU"}, @default_proc=nil>>, "action_dispatch.http_auth_salt"=>"http authentication", "action_dispatch.signed_cookie_salt"=>"signed cookie", "action_dispatch.encrypted_cookie_salt"=>"encrypted cookie", "action_dispatch.encrypted_signed_cookie_salt"=>"signed encrypted cookie", "action_dispatch.cookies_serializer"=>:json, "action_dispatch.cookies_digest"=>nil, "rack.session"=>{}, "rack.session.options"=>{:key=>"rack.session", :path=>"/", :domain=>nil, :expire_after=>nil, :secure=>false, :httponly=>true, :defer=>false, :renew=>false, :sidbits=>128, :cookie_only=>true, :secure_random=>SecureRandom, :id=>"8a8b5f8906289bb00109022394af0832"}, "action_dispatch.request.path_parameters"=>{:controller=>"account/articles", :action=>"new"}}, @filtered_parameters=nil, @filtered_env=nil, @filtered_path=nil, @protocol=nil, @port=nil, @method=nil, @request_method=nil, @remote_ip=nil, @original_fullpath=nil, @fullpath=nil, @ip=nil, @uuid=nil>, @response=#<ActionController::TestResponse:0x007fe85c2cf0a0 @mon_owner=nil, @mon_count=0, @mon_mutex=#<Mutex:0x007fe85c2cef38>, @stream=#<ActionDispatch::Response::Buffer:0x007fe85c2cedd0 @response=#<ActionController::TestResponse:0x007fe85c2cf0a0 ...>, @buf=[], @closed=false>, @header={"X-Frame-Options"=>"SAMEORIGIN", "X-XSS-Protection"=>"1; mode=block", "X-Content-Type-Options"=>"nosniff"}, @status=200, @sending_file=false, @blank=false, @cv=#<MonitorMixin::ConditionVariable:0x007fe85c2ced58 @monitor=#<ActionController::TestResponse:0x007fe85c2cf0a0 ...>, @cond=#<Thread::ConditionVariable:0x007fe85c2ced30>>, @committed=false, @sending=false, @sent=false, @content_type=nil, @charset=nil, @cache_control={}, @etag=nil>, @params={}, @_view_context_class=#<Class:0x007fe85c2c7620>, @_lookup_context=#<ActionView::LookupContext:0x007fe85d1615a0 @details_key=nil, @details={:locale=>[:en], :formats=>[:html, :text, :js, :css, :ics, :csv, :vcf, :png, :jpeg, :gif, :bmp, :tiff, :mpeg, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :pdf, :zip], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder, :haml]}, @skip_default_locale=false, @cache=true, @prefixes=["", "account/articles"], @rendered_format=nil, @view_paths=#<ActionView::PathSet:0x007fe85d1614d8 @paths=[#<ActionView::OptimizedFileSystemResolver:0x007fe85d37fb48 @pattern=":prefix/:action{.:locale,}{.:formats,}{+:variants,}{.:handlers,}", @cache=#<ActionView::Resolver::Cache:0x007fe85d37fb20 @data=#<ActionView::Resolver::Cache::SmallCache:0x007fe85d37faf8 @backend={}, @default_proc=#<Proc:0x007fe85f071198@/Users/et/.rvm/gems/ruby-2.2.2/gems/actionview-4.2.5/lib/action_view/template/resolver.rb:49 (lambda)>>>, @path="/Users/et/Documents/projects/test-blog/app/views">, #<ActionView::OptimizedFileSystemResolver:0x007fe85d37feb8 @pattern=":prefix/:action{.:locale,}{.:formats,}{+:variants,}{.:handlers,}", @cache=#<ActionView::Resolver::Cache:0x007fe85d37fe90 @data=#<ActionView::Resolver::Cache::SmallCache:0x007fe85d37fe68 @backend={}, @default_proc=#<Proc:0x007fe85f071198@/Users/et/.rvm/gems/ruby-2.2.2/gems/actionview-4.2.5/lib/action_view/template/resolver.rb:49 (lambda)>>>, @path="/Users/et/.rvm/gems/ruby-2.2.2/gems/devise-3.5.3/app/views">]>>, @_view_renderer=#<ActionView::Renderer:0x007fe85d1613c0 @lookup_context=#<ActionView::LookupContext:0x007fe85d1615a0 @details_key=nil, @details={:locale=>[:en], :formats=>[:html, :text, :js, :css, :ics, :csv, :vcf, :png, :jpeg, :gif, :bmp, :tiff, :mpeg, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :pdf, :zip], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder, :haml]}, @skip_default_locale=false, @cache=true, @prefixes=["", "account/articles"], @rendered_format=nil, @view_paths=#<ActionView::PathSet:0x007fe85d1614d8 @paths=[#<ActionView::OptimizedFileSystemResolver:0x007fe85d37fb48 @pattern=":prefix/:action{.:locale,}{.:formats,}{+:variants,}{.:handlers,}", @cache=#<ActionView::Resolver::Cache:0x007fe85d37fb20 @data=#<ActionView::Resolver::Cache::SmallCache:0x007fe85d37faf8 @backend={}, @default_proc=#<Proc:0x007fe85f071198@/Users/et/.rvm/gems/ruby-2.2.2/gems/actionview-4.2.5/lib/action_view/template/resolver.rb:49 (lambda)>>>, @path="/Users/et/Documents/projects/test-blog/app/views">, #<ActionView::OptimizedFileSystemResolver:0x007fe85d37feb8 @pattern=":prefix/:action{.:locale,}{.:formats,}{+:variants,}{.:handlers,}", @cache=#<ActionView::Resolver::Cache:0x007fe85d37fe90 @data=#<ActionView::Resolver::Cache::SmallCache:0x007fe85d37fe68 @backend={}, @default_proc=#<Proc:0x007fe85f071198@/Users/et/.rvm/gems/ruby-2.2.2/gems/actionview-4.2.5/lib/action_view/template/resolver.rb:49 (lambda)>>>, @path="/Users/et/.rvm/gems/ruby-2.2.2/gems/devise-3.5.3/app/views">]>>>, @_config={}>, @_request=#<ActionController::TestRequest:0x007fe85c35e048 @env={"rack.version"=>[1, 3], "rack.input"=>#<StringIO:0x007fe85f87eca0>, "rack.errors"=>#<StringIO:0x007fe85f87ed40>, "rack.multithread"=>true, "rack.multiprocess"=>true, "rack.run_once"=>false, "REQUEST_METHOD"=>"GET", "SERVER_NAME"=>"example.org", "SERVER_PORT"=>"80", "QUERY_STRING"=>"", "rack.url_scheme"=>"http", "HTTPS"=>"off", "SCRIPT_NAME"=>"", "CONTENT_LENGTH"=>"0", "HTTP_HOST"=>"test.host", "REMOTE_ADDR"=>"0.0.0.0", "HTTP_USER_AGENT"=>"Rails Testing", "action_dispatch.routes"=>#<ActionDispatch::Routing::RouteSet:0x007fe85c6713e8>, "action_dispatch.parameter_filter"=>[:password], "action_dispatch.redirect_filter"=>[], "action_dispatch.secret_token"=>nil, "action_dispatch.secret_key_base"=>"eb526d7f4b0c06b367225a0d32ba8b3c3287ea6d6de798961e6fe33b975d44c2cd3ae9f314f0b96c73029f052d4670bc5a4db850ffc6a73586043089f57bdb3b", "action_dispatch.show_exceptions"=>false, "action_dispatch.show_detailed_exceptions"=>true, "action_dispatch.logger"=>#<ActiveSupport::Logger:0x007fe85d32d528 @progname=nil, @level=0, @default_formatter=#<Logger::Formatter:0x007fe85d32d4b0 @datetime_format=nil>, @formatter=#<ActiveSupport::Logger::SimpleFormatter:0x007fe85d2fc928 @datetime_format=nil>, @logdev=#<Logger::LogDevice:0x007fe85d32d460 @shift_size=nil, @shift_age=nil, @filename=nil, @dev=#<File:/Users/et/Documents/projects/test-blog/log/test.log>, @mutex=#<Logger::LogDevice::LogDeviceMutex:0x007fe85d32d438 @mon_owner=nil, @mon_count=0, @mon_mutex=#<Mutex:0x007fe85d32d3e8>>>>, "action_dispatch.backtrace_cleaner"=>#<Rails::BacktraceCleaner:0x007fe85c2f4aa8 @filters=[#<Proc:0x007fe85c2f4878@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:14>, #<Proc:0x007fe85c2f4850@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:15>, #<Proc:0x007fe85c2f47d8@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:16>, #<Proc:0x007fe85c2f5750@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:29>], @silencers=[#<Proc:0x007fe85c2f59a8@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:19>], @root="/Users/et/Documents/projects/test-blog/">, "action_dispatch.key_generator"=>#<ActiveSupport::CachingKeyGenerator:0x007fe85f4cc580 @key_generator=#<ActiveSupport::KeyGenerator:0x007fe85f4cc5a8 @secret="eb526d7f4b0c06b367225a0d32ba8b3c3287ea6d6de798961e6fe33b975d44c2cd3ae9f314f0b96c73029f052d4670bc5a4db850ffc6a73586043089f57bdb3b", @iterations=1000>, @cache_keys=#<ThreadSafe::Cache:0x007fe85f4cc558 @backend={"signed_global_ids64"=>"0\xF4/#*5\xF2\x0F\xB2\x101\v~\xC5\x89\xFF\xDB\x11\xCB(U\xFA\xF87\x13Evz:\xAD\xD6\xA3r\x96\x9A\x82\x17\x84\tR\xF2A\xADV\x85u?^N\xBCT\x84\x10\x11\xD9\xC9>n\xA1\f\x06\xAAuU"}, @default_proc=nil>>, "action_dispatch.http_auth_salt"=>"http authentication", "action_dispatch.signed_cookie_salt"=>"signed cookie", "action_dispatch.encrypted_cookie_salt"=>"encrypted cookie", "action_dispatch.encrypted_signed_cookie_salt"=>"signed encrypted cookie", "action_dispatch.cookies_serializer"=>:json, "action_dispatch.cookies_digest"=>nil, "rack.session"=>{}, "rack.session.options"=>{:key=>"rack.session", :path=>"/", :domain=>nil, :expire_after=>nil, :secure=>false, :httponly=>true, :defer=>false, :renew=>false, :sidbits=>128, :cookie_only=>true, :secure_random=>SecureRandom, :id=>"8a8b5f8906289bb00109022394af0832"}, "action_dispatch.request.path_parameters"=>{:controller=>"account/articles", :action=>"new"}}, @filtered_parameters=nil, @filtered_env=nil, @filtered_path=nil, @protocol=nil, @port=nil, @method=nil, @request_method=nil, @remote_ip=nil, @original_fullpath=nil, @fullpath=nil, @ip=nil, @uuid=nil>, @view_flow=#<ActionView::OutputFlow:0x007fe85a962d88 @content={}>, @output_buffer="", @virtual_path=nil, @rendered_views=#<ActionView::TestCase::Behavior::RenderedViewsCollection:0x007fe85a962b30 @rendered_views={}>> does not implement: article
     # ./spec/views/account/articles/new.html.haml_spec.rb:6:in `block (2 levels) in <top (required)>'

Finished in 1.11 seconds (files took 6.26 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./spec/views/account/articles/new.html.haml_spec.rb:9 # account/articles/new renders new article form

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/35240236/how-can-i-stub-a-controller-helper-method-in-a-view-spec-with-rspec-3-4

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