如何使用RSpec测试带参数的方法?

时间:2017-12-09 07:35:24

标签: ruby rspec3

我有以下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。我做错了什么?任何见解都表示赞赏。

3 个答案:

答案 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