我有以下RSpec:
describe Job do
let(:job) { Job.new }
describe 'run_job' do
context 'success' do
my_param = [{"job1" => "run"}, {"job2" => "run again"}]
it 'should pass' do
test_result = job.run_job(my_param)
expect(test_result[0]["job1"]).to eq("run")
end
end
end
end
方法:
Class Job
def run_job(my_param)
# puts "#{my_param}"
my_param.each do|f|
# do something
end
end
end
当我运行测试时,我收到以下错误
NoMethodError:
undefined method `each' for nil:NilClass
我在控制台中打印出my_param
并看到传递给测试的同一个对象[{"job1" => "run"}, {"job2" => "run again"}]
。在调用my_param
时,我不知道为什么nil
为.each
。我做错了什么?任何见解都表示赞赏。
答案 0 :(得分:2)
my_param
应在it
块内定义,或者您应使用let
来定义my_param
在其中阻止
describe Job do
let(:job) { Job.new }
describe 'run_job' do
context 'success' do
it 'should pass' do
my_param = [{"job1" => "run"}, {"job2" => "run again"}]
test_result = job.run_job(my_param)
expect(test_result[0]["job1"]).to eq("run")
end
end
end
end
使用let
describe Job do
let(:job) { Job.new }
describe 'run_job' do
context 'success' do
let(:my_param) { [{"job1" => "run"}, {"job2" => "run again"}] }
it 'should pass' do
test_result = job.run_job(my_param)
expect(test_result[0]["job1"]).to eq("run")
end
end
end
end
在阻止前使用
describe Job do
let(:job) { Job.new }
describe 'run_job' do
context 'success' do
before(:all) do
@my_param = [{"job1" => "run"}, {"job2" => "run again"}]
end
it 'should pass' do
test_result = job.run_job(@my_param)
expect(test_result[0]["job1"]).to eq("run")
end
end
end
end
答案 1 :(得分:0)
一种方法是在前一块中定义并将实例变量形成为;
dos2unix
或
但最好的方法是使用let:
before { @my_param = [{"job1" => "run"}, {"job2" => "run again"}] }
答案 2 :(得分:0)
Better Specs建议使用let
分配变量:
describe Job do
let(:job) { Job.new }
describe 'run_job' do
context 'success' do
let(:my_param) { [{"job1" => "run"}, {"job2" => "run again"}] }
it 'should pass' do
test_result = job.run_job(my_param)
expect(test_result[0]["job1"]).to eq("run")
end
end
end
end