2017-02-14 7 views
0

요리법에 chefspec/unit 테스트를 쓰려고합니다. 나는 문제에 직면하고있다. 아래 코드에 단위 테스트 케이스를 작성해야합니다. 내가 코드의 마지막 문장에 대해 언급하면, 테스트는 성공적으로 끝났지 만 그 문장을 적절한 방법으로 써야한다. 도와 줘서 고맙다.chefspec/unit 테스트에서 내 요리법의 코드를 확인하는 방법

powershell_script 'Delete ISO from temp directory' do 
    code <<-EOH 
      [System.IO.File]::Delete("#{iso_path}") 
      [System.IO.File]::Delete("#{config_path}") 
      EOH 
    guard_interpreter :powershell_script 
    only_if { File.exists?(iso_path)} 
end 
+1

알다시피, 일부 파일을 삭제하려고합니다. 요리사가'file' 리소스를 가지고 있기 때문에 파워 쉘이 필요하지 않습니다. –

+0

@DracoAter 임시 디렉토리가있는 경우에만 ISO를 삭제하려고합니다. 이 블록의 단위 테스트를 위해 powershell 리소스를 사용했지만 제대로 작동하지만 유닛 테스트를 올바르게 작성하기 위해서는 조건을 잡아야합니다. –

+0

정확히'file' 리소스가하는 일입니다. 파일이 있으면 파일을 삭제합니다. 기존의 멱등 원천 자원 (예 : 파일, 디렉토리, 템플리트)을 비 멱등 원 (예 : execute, bash, powershell_script)보다 선호해야합니다. –

답변

0

처음에는 코드가 의미가 없습니다. guard_interpreter 세트가 있지만 guard 절은 명령 문자열이 아닌 Ruby 코드 블록입니다. 그 외에는 다른 것을 시험해보십시오. 기존 파일과 기존 파일을 모두 테스트하는 방법을 구체적으로 나타내는 경우 을 사용하여 File.exists?을 설정하여 준비 값을 반환합니다.

0

우선. 필요한 것은 파일을 삭제하는 것이고 코드의 경우 코드에 따라 file 리소스를 사용해야합니다.

[iso_path, config_path].each do |path| 
    file path do 
    action :delete 
    end 
end 

File은 멱등 원이다. 즉, 요리사가 자원을 변경해야하는 경우 귀하를 확인합니다. 이 경우 Chef는 파일이있는 경우에만 파일을 삭제합니다.

Powershell_script (및 기타 모든 script 리소스)은 멱등 원이 아닙니다. 즉, 자원을 실행해야한다면 guard을 제공하여 스스로 확인하십시오. 가드는 only_if 또는 not_if 블록입니다. 실제로 가드에 루비를 쓰고 있기 때문에 guard_interpreter :powershell_script 행을 제거해야합니다.

powershell_script 'Delete ISO from temp directory' do 
    code <<-EOH 
    [System.IO.File]::Delete("#{iso_path}") 
    [System.IO.File]::Delete("#{config_path}") 
    EOH 
    only_if { File.exists?(iso_path) } 
end 

테스트를 완료했습니다. 테스트 file 리소스가 쉽습니다. 이미 이해할 수 있습니다. 그러나 powershell_script을 테스트하는 것이 더 어렵습니다. File.exists?(iso_path) 호출을 스텁링해야합니다. 당신은 그런 식으로 작업을 수행 할 수 있습니다

describe 'cookbook::recipe' do 
    context 'with iso file' do 
    let! :subject do 
     expect(::File).to receive(:exists?).with('<iso_path_variable_value>').and_return true 
     allow(::File).to receive(:exists?).and_call_original 
     ChefSpec::Runner.new(platform: 'windows', version: '2008R2').converge described_recipe 
    end 

    it { shold run_powershell_script 'Delete ISO from temp directory' } 
    end 

    context 'without iso file' do 
    let! :subject do 
     expect(::File).to receive(:exists?).with('<iso_path_variable_value>').and_return false 
     allow(::File).to receive(:exists?).and_call_original 
     ChefSpec::Runner.new(platform: 'windows', version: '2008R2').converge described_recipe 
    end 

    it { shold_not run_powershell_script 'Delete ISO from temp directory' } 
    end 
end 

당신은 당신이 file 자원을 테스트에 비교 할 필요가 얼마나 더 많은 작업을 볼 수 있나요?