如何使用Shoulda测试辅助方法并设置参数和请求值?

时间:2009-09-02 14:54:52

标签: ruby-on-rails unit-testing shoulda

我正在使用rails 2.2.2,并想知道如何设置params值来测试我的帮助方法。

我找到了一些示例,让您使用辅助方法运行测试但是当我直接在方法中使用请求或params值时,它对我不起作用。

require 'test_helper'

class ProductHelperTest < Test::Unit::TestCase
  include ProductHelper

  context 'ProductHelper' do
    should 'build the link' do
      assert_equal '', build_link
    end
  end
end

当使用请求或参数值时,我将收到一个错误,即局部变量或方法未定义。我该如何设定价值?

使用请求值时来自shoulda的错误,并且在使用params值时它将是相同的消息。

1) Error:
test: ProductHelper should build the link. (ProductHelperTest):
NameError: undefined local variable or method `request` for #<ProductHelperTest:0x33ace6c>
  /vendor/rails/actionpack/lib/action_controller/test_process.rb:471:in `method_missing`
  /app/helpers/products_helper.rb:14:in `build_link`
  ./test/unit/product_helper_test.rb:10:in `__bind_1251902384_440357`
  /vendor/gems/thoughtbot-shoulda-2.0.5/lib/shoulda/context.rb:254:in `call`
  /vendor/gems/thoughtbot-shoulda-2.0.5/lib/shoulda/context.rb:254:in `test: ProductHelper should build the link. `
  /vendor/rails/activesupport/lib/active_support/testing/setup_and_teardown.rb:94:in `__send__`
  /vendor/rails/activesupport/lib/active_support/testing/setup_and_teardown.rb:94:in `run`

3 个答案:

答案 0 :(得分:3)

我想您必须使用request或在测试中定义模拟对象来模拟对paramsmocha的调用:

# Assuming ProductHelper implementation
module ProductHelper
  def build_link
    "#{request.path}?#{params[:id]}"
  end
end

class ProductHelperTest < Test::Unit::TestCase
  include ProductHelper

  # mock by defining a method
  def params
    { :controller => "test", :id => "23" }
  end

  # mock request.path using `mocha` # => "my_url"
  def request
    mock(:path => "my_url")
  end

  context 'ProductHelper' do
    should 'build the link' do
      assert_equal 'my_url?23', build_link
    end
  end
end

我希望这会有所帮助:)

答案 1 :(得分:0)

作为一个注释,如果您使用的是Rails 2.3.x或任何使用ActionView :: TestCase的东西 - 那么您真正需要做的只是在测试中定义私有参数方法。

e.g

require 'test_helper'

class BookmarksHelperTest < ActionView::TestCase

  context "with an applied filter of my bookmarks" do
    setup do
      expects(:applied_filters).returns({:my_bookmarks => true})
    end

    should "not be able to see it when other filters are called using my_bookmarks_filter" do
      assert_equal other_filters(:my_bookmarks), {}
    end
  end

  private

    def params
      {}
    end

end

通过将params定义为ActionView :: TestCase

中的方法,您甚至可以做得更好

答案 2 :(得分:0)

这也有效: controller.params = {:filter => {:user_id => 1}

以下是一个例子:

require 'test_helper'

class BookmarksHelperTest < ActionView::TestCase

  def test_some_helper_method
    controller.params = {:filter => {:user_id => 1}
    #... Rest of your test
  end
end