出错提示
C:\Users\gongjue\dotfiles\engineering\unit-test>busted busted-simple.lua
鈼忊棌鈼忊湵
3 successes / 0 failures / 1 error / 0 pending : 0.0 seconds
Error 鈫?busted-simple.lua @ 29
Busted unit testing framework should be awesome should have mocks and spies for functional tests
busted-simple.lua:30: module 'thing_module' not found:
no field package.preload['thing_module']
no file './src/thing_module.lua'
no file './src/thing_module/thing_module.lua'
no file './src/thing_module/init.lua'
no file 'C:\local\LuaRocks-3.0.2\systree/share/lua/5.3/thing_module.lua'
no file 'C:\local\LuaRocks-3.0.2\systree/share/lua/5.3/thing_module/init.lua'
no file '%LUA_PATH%'
no file './csrc/thing_module.dll'
no file './csrc/thing_module/thing_module.dll'
no file 'C:\local\LuaRocks-3.0.2\systree/lib/lua/5.3/thing_module.dll'
no file '%LUA_CPATH%'
问题分析
从错误输出可以看到 lua 在 require 时没有搜索当前路径下的文件。所以把当前路径加到 LUA_PATH
中就能解决问题。
解决办法
按照笔者 Windows 平台 Luarocks 3.0.2 编译安装 的方法,LuaRocks安装在 C:\local\LuaRocks-3.0.2
,打开 C:\local\LuaRocks-3.0.2\systree\bin\busted.bat
可看到原始内容是:
@echo off
set "LUAROCKS_SYSCONFDIR=C:\local\LuaRocks-3.0.2"
set "LUA_PATH=C:\local\LuaRocks-3.0.2\systree/share/lua/5.3/?.lua;C:\local\LuaRocks-3.0.2\systree/share/lua/5.3/?/init.lua;%%LUA_PATH%%"
set "LUA_CPATH=C:\local\LuaRocks-3.0.2\systree/lib/lua/5.3/?.dll;%%LUA_CPATH%%"
set "LUA_INIT=local k,l,_=pcall(require,'luarocks.loader') _=k and l.add_context('busted','2.0.rc13-0')"
"C:\local\lua-5.3.5\dist\bin\lua.exe" "C:\local\LuaRocks-3.0.2\systree\lib\luarocks\rocks-5.3\busted\2.0.rc13-0\bin\busted" %*
exit /b %ERRORLEVEL%
可见在没有定义 LUA_PATH
的时候是不会读当前路径的。按笔者文章中的做法也的确没有设定。所以按 Lua 默认的路径修改以上 bat 文件(参照 Difference between require and dofile 中列出的一些默认路径,主要增加 .\?.lua
类似的模式来让 Lua 扫描当前文件所在的路径下的文件。修改后如下:
@echo off
set "LUAROCKS_SYSCONFDIR=C:\local\LuaRocks-3.0.2"
set "LUA_PATH=.\?.lua;C:\local\LuaRocks-3.0.2\systree/share/lua/5.3/?.lua;C:\local\LuaRocks-3.0.2\systree/share/lua/5.3/?/init.lua;%%LUA_PATH%%"
set "LUA_CPATH=.\?.dll;.\?53.dll;C:\local\LuaRocks-3.0.2\systree/lib/lua/5.3/?.dll;%%LUA_CPATH%%"
set "LUA_INIT=local k,l,_=pcall(require,'luarocks.loader') _=k and l.add_context('busted','2.0.rc13-0')"
"C:\local\lua-5.3.5\dist\bin\lua.exe" "C:\local\LuaRocks-3.0.2\systree\lib\luarocks\rocks-5.3\busted\2.0.rc13-0\bin\busted" %*
exit /b %ERRORLEVEL%
保存上述内容再次运行就不再报错了。