【问题标题】:Test instance variable is assigned分配了测试实例变量
【发布时间】:2014-07-01 00:48:50
【问题描述】:

我喜欢用它来测试是否设置了正确的实例变量:

it { should assign_to(:resource) }

我再也找不到了https://github.com/thoughtbot/shoulda-matchers

如何取回它或编写自己的匹配器?

他们为什么要删除它?对我来说似乎很有用。

【问题讨论】:

    标签: rspec shoulda


    【解决方案1】:

    这是我在几分钟内拼凑起来的一个快速匹配器:

    RSpec::Matchers.define :set_the_instance_variable do |instance| 
        match do |actual|
            @actual = controller.instance_variable_get(instance)
            @actual == @value
        end
    
        failure_message_for_should do |actual|
            "Expected '#{instance}' to equal #{@value}. However, it did not: \n '#{@actual.inspect}' \n '#{@value.inspect}'"
        end
    
        failure_message_for_should_not do |actual|
            "Expected '#{instance}' to not equal #{@value}. However, it did: \n '#{@actual.inspect}' \n '#{@value.inspect}'"        end
    
        description do
            "'#{instance}' should equal #{@value}."
        end
    
        def to(value)
            @value = value
            self
        end
    end
    

    用法

    it { should set_the_instance_variable(:@folder).to(parent_folder)}
    

    【讨论】:

      【解决方案2】:

      如果这个变量不是来自你的公共接口,那么测试它是没有意义的。如果您有访问器,您可以使用respond_to 结合eq 来检查值是否设置正确。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-06-01
        • 2022-12-22
        • 1970-01-01
        • 1970-01-01
        • 2015-10-28
        • 1970-01-01
        • 2021-06-18
        • 2011-09-07
        相关资源
        最近更新 更多