How do I set a default format in RSpec controller specs?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







1















Rails app has the controller with actions which response html and json formats. In specs I should specify format: 'json' for all requests:



it 'returns list of entities' do
get :list, format: 'json'
...
end


Is there a way to avoid write format: 'json' for every example? Something like this:



context 'json', format: 'json' do
it 'returns list of entities' do
get :list
...
end
end









share|improve this question




















  • 1





    Edited the title for search-ability. This is also a potential duplicate of stackoverflow.com/questions/11022839/… - which currently does not seem to have a currently working answer.

    – max
    Nov 16 '18 at 17:26


















1















Rails app has the controller with actions which response html and json formats. In specs I should specify format: 'json' for all requests:



it 'returns list of entities' do
get :list, format: 'json'
...
end


Is there a way to avoid write format: 'json' for every example? Something like this:



context 'json', format: 'json' do
it 'returns list of entities' do
get :list
...
end
end









share|improve this question




















  • 1





    Edited the title for search-ability. This is also a potential duplicate of stackoverflow.com/questions/11022839/… - which currently does not seem to have a currently working answer.

    – max
    Nov 16 '18 at 17:26














1












1








1


1






Rails app has the controller with actions which response html and json formats. In specs I should specify format: 'json' for all requests:



it 'returns list of entities' do
get :list, format: 'json'
...
end


Is there a way to avoid write format: 'json' for every example? Something like this:



context 'json', format: 'json' do
it 'returns list of entities' do
get :list
...
end
end









share|improve this question
















Rails app has the controller with actions which response html and json formats. In specs I should specify format: 'json' for all requests:



it 'returns list of entities' do
get :list, format: 'json'
...
end


Is there a way to avoid write format: 'json' for every example? Something like this:



context 'json', format: 'json' do
it 'returns list of entities' do
get :list
...
end
end






ruby-on-rails ruby rspec rspec-rails






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 16 '18 at 17:24









max

46.8k1060106




46.8k1060106










asked Nov 16 '18 at 15:13









vovanvovan

477614




477614








  • 1





    Edited the title for search-ability. This is also a potential duplicate of stackoverflow.com/questions/11022839/… - which currently does not seem to have a currently working answer.

    – max
    Nov 16 '18 at 17:26














  • 1





    Edited the title for search-ability. This is also a potential duplicate of stackoverflow.com/questions/11022839/… - which currently does not seem to have a currently working answer.

    – max
    Nov 16 '18 at 17:26








1




1





Edited the title for search-ability. This is also a potential duplicate of stackoverflow.com/questions/11022839/… - which currently does not seem to have a currently working answer.

– max
Nov 16 '18 at 17:26





Edited the title for search-ability. This is also a potential duplicate of stackoverflow.com/questions/11022839/… - which currently does not seem to have a currently working answer.

– max
Nov 16 '18 at 17:26












1 Answer
1






active

oldest

votes


















2














This is adapted from https://stackoverflow.com/a/39399215/544825 but for controller specs.



Tested on: RSpec 3.8, Rails 5.2.1



This module uses metaprogramming to redefine the get, post etc methods and a memoized let helper (default_format) instead of metadata.



It basically just merges format: default_format into the arguments and calls the original implementation.



# spec/support/default_format.rb
module DefaultFormat
extend ActiveSupport::Concern

included do
let(:default_format) {}
prepend RequestHelpersCustomized
end

module RequestHelpersCustomized
l = lambda do |path, **kwargs|
kwargs[:format] ||= default_format if default_format
super(path, kwargs)
end
%w(get post patch put delete).each do |method|
define_method(method, l)
end
end
end


And then include this module in your rails_helper.rb or spec_helper.rb(if you only have one test setup file):



require 'support/default_format'

RSpec.configure do |config|
# ...
config.include DefaultFormat, type: :controller
# ...
end


Usage:



context 'json' do
let(:default_format) { :json }
end


I don't think this can be done with example metadata as its not available from within an example (which is where the get method is called).






share|improve this answer


























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53340562%2fhow-do-i-set-a-default-format-in-rspec-controller-specs%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    This is adapted from https://stackoverflow.com/a/39399215/544825 but for controller specs.



    Tested on: RSpec 3.8, Rails 5.2.1



    This module uses metaprogramming to redefine the get, post etc methods and a memoized let helper (default_format) instead of metadata.



    It basically just merges format: default_format into the arguments and calls the original implementation.



    # spec/support/default_format.rb
    module DefaultFormat
    extend ActiveSupport::Concern

    included do
    let(:default_format) {}
    prepend RequestHelpersCustomized
    end

    module RequestHelpersCustomized
    l = lambda do |path, **kwargs|
    kwargs[:format] ||= default_format if default_format
    super(path, kwargs)
    end
    %w(get post patch put delete).each do |method|
    define_method(method, l)
    end
    end
    end


    And then include this module in your rails_helper.rb or spec_helper.rb(if you only have one test setup file):



    require 'support/default_format'

    RSpec.configure do |config|
    # ...
    config.include DefaultFormat, type: :controller
    # ...
    end


    Usage:



    context 'json' do
    let(:default_format) { :json }
    end


    I don't think this can be done with example metadata as its not available from within an example (which is where the get method is called).






    share|improve this answer






























      2














      This is adapted from https://stackoverflow.com/a/39399215/544825 but for controller specs.



      Tested on: RSpec 3.8, Rails 5.2.1



      This module uses metaprogramming to redefine the get, post etc methods and a memoized let helper (default_format) instead of metadata.



      It basically just merges format: default_format into the arguments and calls the original implementation.



      # spec/support/default_format.rb
      module DefaultFormat
      extend ActiveSupport::Concern

      included do
      let(:default_format) {}
      prepend RequestHelpersCustomized
      end

      module RequestHelpersCustomized
      l = lambda do |path, **kwargs|
      kwargs[:format] ||= default_format if default_format
      super(path, kwargs)
      end
      %w(get post patch put delete).each do |method|
      define_method(method, l)
      end
      end
      end


      And then include this module in your rails_helper.rb or spec_helper.rb(if you only have one test setup file):



      require 'support/default_format'

      RSpec.configure do |config|
      # ...
      config.include DefaultFormat, type: :controller
      # ...
      end


      Usage:



      context 'json' do
      let(:default_format) { :json }
      end


      I don't think this can be done with example metadata as its not available from within an example (which is where the get method is called).






      share|improve this answer




























        2












        2








        2







        This is adapted from https://stackoverflow.com/a/39399215/544825 but for controller specs.



        Tested on: RSpec 3.8, Rails 5.2.1



        This module uses metaprogramming to redefine the get, post etc methods and a memoized let helper (default_format) instead of metadata.



        It basically just merges format: default_format into the arguments and calls the original implementation.



        # spec/support/default_format.rb
        module DefaultFormat
        extend ActiveSupport::Concern

        included do
        let(:default_format) {}
        prepend RequestHelpersCustomized
        end

        module RequestHelpersCustomized
        l = lambda do |path, **kwargs|
        kwargs[:format] ||= default_format if default_format
        super(path, kwargs)
        end
        %w(get post patch put delete).each do |method|
        define_method(method, l)
        end
        end
        end


        And then include this module in your rails_helper.rb or spec_helper.rb(if you only have one test setup file):



        require 'support/default_format'

        RSpec.configure do |config|
        # ...
        config.include DefaultFormat, type: :controller
        # ...
        end


        Usage:



        context 'json' do
        let(:default_format) { :json }
        end


        I don't think this can be done with example metadata as its not available from within an example (which is where the get method is called).






        share|improve this answer















        This is adapted from https://stackoverflow.com/a/39399215/544825 but for controller specs.



        Tested on: RSpec 3.8, Rails 5.2.1



        This module uses metaprogramming to redefine the get, post etc methods and a memoized let helper (default_format) instead of metadata.



        It basically just merges format: default_format into the arguments and calls the original implementation.



        # spec/support/default_format.rb
        module DefaultFormat
        extend ActiveSupport::Concern

        included do
        let(:default_format) {}
        prepend RequestHelpersCustomized
        end

        module RequestHelpersCustomized
        l = lambda do |path, **kwargs|
        kwargs[:format] ||= default_format if default_format
        super(path, kwargs)
        end
        %w(get post patch put delete).each do |method|
        define_method(method, l)
        end
        end
        end


        And then include this module in your rails_helper.rb or spec_helper.rb(if you only have one test setup file):



        require 'support/default_format'

        RSpec.configure do |config|
        # ...
        config.include DefaultFormat, type: :controller
        # ...
        end


        Usage:



        context 'json' do
        let(:default_format) { :json }
        end


        I don't think this can be done with example metadata as its not available from within an example (which is where the get method is called).







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 16 '18 at 17:07

























        answered Nov 16 '18 at 16:47









        maxmax

        46.8k1060106




        46.8k1060106
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53340562%2fhow-do-i-set-a-default-format-in-rspec-controller-specs%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Florida Star v. B. J. F.

            Error while running script in elastic search , gateway timeout

            Adding quotations to stringified JSON object values