问题描述
使用
rspec 2.6.4
rails 3.1.6
如何在 Rails 测试控制台中使用 let
变量?
How to use let
variables in rails test console?
1.9.3-p0 :032 > let(:user) { create(:user) }
NoMethodError: undefined method `let' for main:Object
请告知,这里应该需要哪个库?
Please advise, which library should be required here?
例如:下面在控制台中执行以在控制台中使用stub
方法.
For example: below is executed in console to use stub
methods in console.
require 'rspec/mocks/standalone'
是否可以在 rails 控制台中定义和调用 let
变量?
Is it possible, to define and call let
variables in rails console?
推荐答案
如果你对 let
只是创建全局变量没问题,你可以像这样 polyfill:
If you are fine with let
just creating globals, you can polyfill it like this:
def let(name)
Object.send :instance_variable_set, "@#{name}", yield
Object.send :define_method, name do
Object.send :instance_variable_get, "@#{name}"
end
end
用法与 rspec 相同:
Usage is the same as rspec:
irb(main):007:0> let(:foo) { 1 }
=> :foo
irb(main):008:0> foo
=> 1
虽然你真的不应该将你的测试代码粘贴到控制台来调试它.最好使用像 pry 或 byebug 这样的断点工具.
though you really shouldn't be pasting your test code into console to debug it. It's much better to use a breakpoint tool like pry or byebug.
这篇关于如何在 rails 控制台中使用 let 变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!