更改自定义匹配器中的“实际”

时间:2014-06-29 20:12:42

标签: rspec

所以我创建了一个自定义匹配器(参见here to see why I'm not using redirects_to):

RSpec::Matchers.define :redirect_to_location do |expected|

    match do |actual|
        expected == actual.location.gsub('http://test.host/', '')
    end

    failure_message_for_should do |actual|
        "should redirect to #{expected}, instead redirected to #{actual}"
    end

    failure_message_for_should_not do |actual|
        "should not redirect to #{expected}, but did redirect to #{actual}"
    end

    description do
        "should redirect to #{expected}"
    end
end

我在我的规范中使用它:

it { should redirect_to_location "browse/#{folder.id}" }

虽然它有效,但其失败消息却没有:

should redirect to browse/1, instead redirected to #<ActionController::TestResponse:0x007fe039930848>

这应该是:

should redirect to browse/1, instead redirected to bowser/3

如何将actual更新为自定义匹配器中actual.location.gsub('http://test.host/', '')返回的内容?

1 个答案:

答案 0 :(得分:1)

使用实例变量似乎有效:

RSpec::Matchers.define :redirect_to_location do |expected|


    match do |actual|
        @actual = actual.location.gsub('http://test.host', '')
        expected == @actual
    end

    failure_message_for_should do |actual|
        "should redirect to #{expected}, instead redirected to #{@actual}"
    end

    failure_message_for_should_not do |actual|
        "should not redirect to #{expected}, but did redirect to #{@actual}"
    end

    description do
        "should redirect to #{expected}"
    end
end

不确定这是否是正确的方法。