我是 Ruby on Rails 世界的新手。
我注意到至少有一种方法可以从测试用例中访问 Controller 实例变量。
确实,假设这个测试方法:
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:products)
end
products
是包含在相关 Controller 中的实例变量。可以肯定的是,测试用例引用了这个 Controller 。因此 assigns()
方法使用它来检查 Controller 实例变量的散列,从而允许从之前调用此 Controller 的操作的任何其他文件访问任何精确对象。
所以我想知道两个问题:
为什么不创建 Controller 的“绑定(bind)”而不是使用 assigns()
方法?
我想象一个可以做到的版本:
test "should get index" do
get :index
assert_response :success
assert_not_nil @products
end
它不会更短更简洁吗?
绑定(bind)是允许 ERB 文件访问 Controller 实例变量的机制,如以下链接所示:
http://rrn.dk/rubys-erb-templating-system
什么机制不适用于测试用例? assigns()
方法是必不可少的吗?
最佳答案
但是,如果你带来了绑定(bind),这可能会通过但不应该通过
test "should get index" do
@fake_products = [1,2,3]
get :index
assert_response :success
assert_not_nil @fake_products
end
您不一定希望测试中的所有实例变量都与 Controller 中的实例变量相结合。 Assigns 让您可以将您的断言“范围”限定为 Controller 实例变量。
关于ruby-on-rails - assigns() 方法与绑定(bind) - Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11204355/