轨,MINITEST:如何测试控制器
我的控制器看起来像这样的输出:轨,MINITEST:如何测试控制器
class CalculatorController < ApplicationController
def calculate
money = params[:money].to_f
@worktime = divide(money, 25)
end
private
def divide(money, worktime)
output = money/worktime
end
end
我写了这样一个测试:
require 'test_helper'
class CalculatorControllerTest < ActionDispatch::IntegrationTest
test "response" do
get calculate_path
assert_equal 200, response.status
end
end
该测试通过。现在,我想编写一个测试,检查输出是否正确。我尝试这样做:
require 'test_helper'
class CalculatorControllerTest < ActionDispatch::IntegrationTest
test "response" do
get calculate_path(money: 25)
assert_equal 200, response.status
assert_equal 1, @response.worktime
end
end
但出现此错误:NoMethodError: undefined method
worktime'`
如何测试控制器的输出? (在我的情况@worktime)
这里有一个很好的书面记录在导轨5的变化测试: http://blog.bigbinary.com/2016/04/19/changes-to-test-controllers-in-rails-5.html
在Rails 4,你可以使用 “受让人”,以检查:
assert_equal 1, assigns(:worktime)
通过在测试组的Gemfile中包含rails-controller-testing gem https://github.com/rails/rails-controller-testing,您仍然可以拥有此功能。这里更多来自DHH:
非常感谢!我将如何测试我的方法'鸿沟'?例如:assert_equal 1,divide(25/25)。 – Metaphysiker
我不能说没有看到更多的应用程序(无论如何,这超出了SO的范围),但通常这样的逻辑应该可以在它可以被单元测试的模型中。 –
在Ruby @variables
是实例变量。不是全局变量。实例变量始终是私有的*。
因此@worktime
是属于CalculatorController
的实例变量 - 不是CalculatorControllerTest
。
Ruby允许您在不声明的情况下访问实例变量。
所以这个例子:
require 'test_helper'
class CalculatorControllerTest < ActionDispatch::IntegrationTest
test "response" do
get calculate_path(money: 25)
assert_equal 200, response.status
assert_equal 1, @response.worktime
end
end
实际上是在实践中:
require 'test_helper'
class CalculatorControllerTest < ActionDispatch::IntegrationTest
test "response" do
get calculate_path(money: 25)
assert_equal 200, response.status
assert_equal 1, nil.worktime # since @worktime is not declared in this scope.
end
end
以前,你可以窥探控制器与assigns
内部运作这是在Rails的5删除您可以恢复它为with a gem,但对于新的应用程序,你应该使用不同的方法来测试 - 你应该测试你的控制器,通过测试响应代码和JSON或HTML输出的实际输出。不是它的工作方式。
require 'test_helper'
class CalculatorControllerTest < ActionDispatch::IntegrationTest
test "response" do
get calculate_path(money: 25)
assert_equal 200, response.status
assert_select "#result", "1"
end
end
你能给我一个工作的例子吗?或者一个网站的进一步说明?谢谢 – Metaphysiker
http://guides.rubyonrails.org/testing.html#integration-testing – max
您使用的是哪个版本的Rails?在Rails 4中,你可以检查它。在Rails 5中,你必须带上另一块来做你想做的事情。 –
@MichaelChaney Rails 5.0.0.1我需要带什么?谢谢 – Metaphysiker
看到我的回答如下,太多评论:) –