Testing rendering of a given layout with RSpec & Rails

后端 未结 11 1475
滥情空心
滥情空心 2020-12-24 12:31

Is it possible to test the use of a given layout using RSpec with Rails, for example I\'d like a matcher that does the following:

response.should use_layout(         


        
11条回答
  •  不知归路
    2020-12-24 13:02

    Here's a version of dmcnally's code that allows no arguments to be passed, making "should use_layout" and "should_not use_layout" work (to assert that the controller is using any layout, or no layout, respectively - of which I would expect only the second to be useful as you should be more specific if it is using a layout):

    class UseLayout
       def initialize(expected = nil)
         if expected.nil?
           @expected = nil
         else
           @expected = 'layouts/' + expected
         end
       end
       def matches?(controller)
         @actual = controller.layout
         #@actual.equal?(@expected)
         if @expected.nil?
           @actual
         else
           @actual == @expected
         end
       end
       def failure_message
         if @expected.nil?
           return 'use_layout expected a layout to be used, but none was', 'any', @actual
         else
           return "use_layout expected #{@expected.inspect}, got #{@actual.inspect}", @expected, @actual
         end
       end
       def negative_failure_message
         if @expected.nil?
           return "use_layout expected no layout to be used, but #{@actual.inspect} found", 'any', @actual
         else
           return "use_layout expected #{@expected.inspect} not to equal #{@actual.inspect}", @expected, @actual
         end
       end
    end
    
    
    def use_layout(expected = nil)
       UseLayout.new(expected)
    end
    

提交回复
热议问题