[英]how do I set up factory_girl in my test_helper.rb file to use with shoulda?
[英]How do I test helper methods using Shoulda and set the params and request values?
我正在使用Rails 2.2.2,想知道如何设置params值来测试辅助方法。
我找到了一些示例来让您使用辅助方法运行测试,但是当我直接在该方法中使用request或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
使用request或params值时,我会得到一个错误,即未定义局部变量或方法。 我将如何设置该值?
使用请求值时,来自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`
我猜您必须使用mocha
或在测试中定义模拟对象来模拟对request
和params
调用:
# 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
我希望这有帮助 :)
注意,如果您使用的是Rails 2.3.x或任何使用ActionView :: TestCase的东西-那么您真正需要做的就是在测试中定义一个私有的params方法。
例如
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
您甚至可以通过将参数定义为ActionView :: TestCase中的方法来做得更好
这也适用: 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.