我想測驗else以下 ruby?? 代碼的分支:
SCHEMA_SOURCE = if File.exist? SCHEMA_FILENAME
SCHEMA_FILENAME
else
ContentfulApi::Http
end
我找不到模擬檔案不存在的方法SCHEMA_FILENAME。這是我嘗試過的測驗的簡化版本,以及錯誤:
it 'fails to find file when it does not exist' do
allow(File).to receive(:exists?).and_return(false)
expect(File.exist?(ContentfulApi::SCHEMA_FILENAME)).to be_falsey
end
it 'fails to find file when it does not exist' do
allow(File).to receive(:exists?).with(ContentfulApi::SCHEMA_FILENAME)\
.and_return(false)
expect(File.exist?(ContentfulApi::SCHEMA_FILENAME)).to be_falsey
end
這些都因錯誤而失敗
預期:假值得
到:真
it 'fails to find file when it does not exist' do
File.stub(:exists?) { false }
expect(File.exist?(ContentfulApi::SCHEMA_FILENAME)).to be_falsey
end
it 'fails to find file when it does not exist' do
File.stub!(:exists?).with(ContentfulApi::SCHEMA_FILENAME)\
.and_return(false)
expect(File.exist?(ContentfulApi::SCHEMA_FILENAME)).to be_falsey
end
這些都因錯誤而失敗
檔案:類的未定義方法“存根”
我的前兩次嘗試遵循Method Stubs檔案中的示例,盡管該檔案中未探討的類和物件之間可能存在區別。(雖然類是Ruby 中的物件,對吧?)
后兩次嘗試遵循較舊的檔案。
即使檔案確實存在,我應該如何存根File.exist? SCHEMA_FILENAME以使其回傳?false
N.B. The approaches in these similar questions do not work:
- rspec to stub several File.exists? calls
- Rspec -- need to stub File.open that gets called in another file
- rspec undefined method stub for model
- how to reset expectations on a mocked class method?
- How do I stub out a specific file with rspec?
- Can't stub things with Rspec
- rspec 3 - stub a class method
uj5u.com熱心網友回復:
你在嘲笑File.exists?和打電話File.exist?。
請注意,如果您已經verify_partial_doubles設定并且應該設定,RSpec 將不允許您模擬不存在的方法。
RSpec.configure do |config|
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
end
RSpec.describe File do
it 'cannot mock a method whcih does not exist' do
allow(File).to receive(:dslkfjalk).and_return(true)
end
end
Failures:
1) File cannot mock a method whcih does not exist
Failure/Error: allow(File).to receive(:dslkfjalk).and_return(true)
File does not implement: dslkfjalk
但File確實有兩者exist?和exists?方法。File.exists?已棄用并從檔案中洗掉,但我想它仍然......存在。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/443722.html
