Last active
June 30, 2017 16:55
-
-
Save mattheworiordan/9020970 to your computer and use it in GitHub Desktop.
Allow testing of locals when rendering Controllers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def assigns_local(key) | |
controller.instance_variable_get('@patched_locals')[key] | |
end | |
def patch_controller_render_to_support_locals(controller) | |
def controller.render(options = nil, extra_options = {}, &block) | |
[options, extra_options].select { |o| o.kind_of?(Hash) }.each do |option_hash| | |
if option_hash.include?(:locals) | |
@patched_locals = option_hash[:locals] | |
end | |
end | |
super(options, extra_options, &block) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class FooController < ApplicationController | |
def index | |
render locals: { | |
foos: Foo.all | |
} | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'spec_helper' | |
describe FooController do | |
describe :index do | |
it 'should render locals' do | |
expect(response).to render_template('index') | |
expect(assigns_local(:foos)).to eq(Foo.all) | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'support/assigns_locals_helper.rb' | |
config.before(:each, type: :controller) do | |
patch_controller_render_to_support_locals controller | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
assert_template 'index', locals: { foos: Foo.all }
seems to work too