问题
using
rspec 2.6.4
rails 3.1.6
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?
For example: below is executed in console to use stub
methods in console.
require 'rspec/mocks/standalone'
Is it possible, to define and call let
variables in rails console?
回答1:
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
Usage is the same as rspec:
irb(main):007:0> let(:foo) { 1 }
=> :foo
irb(main):008:0> foo
=> 1
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.
回答2:
let
in rspec
is not much more than a lazily executed and memoized method definition. If you must have in the irb you could define it like this:
$ cat let.rb
def let(sym)
$let ||= {}
define_method sym do
$let[sym] ||= yield
end
end
require './let
in irb or place it in .irbrc
and you have your rspec-like let
. Note, that rspec reevaluates let
in each new example (it
or specify
block). Since you don't have them in irb you may need to clear your let
cache manually ($let = {}
) to force re-evaluation.
来源:https://stackoverflow.com/questions/48436445/how-to-use-let-variables-in-rails-console