问题描述
我有一个访问索引视图并进行简单断言的测试(这里是一个简化版本):
setup { login(@user) }
should 'have expected content' do
get :index
assert_match 'some content',response.body
end
测试需要 > 100 秒才能完成,经过一些调试,我发现罪魁祸首是 image_tag
= image_tag 'file-csv-solid.svg',alt: 'CSV Download'
图像本身存储在 assets/images/file-csv-solid.svg
中。查看应用程序时,图像会在合理的时间内按预期呈现。即使在测试中,图像也以正确的路径呈现:
<img alt="CSV Download" src="/assets/file-csv-solid-cf0f63e5f766b9eddbc3d4f926a0f4d3c085bd52855958215c9dc659d308075a.svg">
唯一的问题是,渲染时间太长了。在我的日志中,我看到了这一点:
Rendered path/to/index.haml (Duration: 106283.1ms | Allocations: 71099973)
当我注释掉 image_tag
时,同样的测试只需几毫秒即可完成。
我的问题是:为什么渲染图像标签需要这么长时间,我该如何加快速度(或者只是跳过它的渲染——我实际上并不关心测试中的图像)?
>我正在使用 Rails 6.0.3.4
。我假设我只需要在我的测试配置中调整一些 config.assets.*
设置,但我尝试了一些不同的设置但没有成功。
解决方法
我似乎找到了问题所在。我认为 rails/sprockets 试图在测试中预编译和缓存资产,但由于一个不相关的问题,预编译命令引发了错误。
感谢上面@eux 的评论,我尝试将我的 svg 换成现有的 jpg,并且测试速度很快。然后我尝试将它换成不同的现有 svg,它仍然很快。所以我开始寻找我尝试使用的 svg 和现有的 svg 之间的区别。不同之处在于 return 5 * 4 * 3 * 2 * 1 * 1
和 interface ColorsInterface {
bgColor: keyof ThemeVars['colors'];
textColor: keyof ThemeVars['colors'];
}
const colorMap = new Map<string,ColorsInterface>([
['standard',{ bgColor: 'primaryNormal',textColor: 'white' }],['accent',{ bgColor: 'accentNormal',['neutral',{ bgColor: 'grayExtraDark',['flat',{ bgColor: 'white',textColor: 'primaryNormal' }],['text',textColor: 'grayExtraDark' }],['disabled',{ bgColor: 'grayLight',textColor: 'grayDark' }],]);
export const ButtonWrapper = styled.button<ButtonInterface>`
${props =>
props.buttonType &&
css`
background-color: ${props.theme.colors[colorMap.get(props.buttonType).bgColor]};
color: ${colorMap.get(props.buttonType)?.textColor};
`}
`;
中存在一个,而我尝试添加的新的没有。我运行 tmp/cache/assets/sprockets/
以尝试将我的 svg 也缓存在那里,并看到一个不相关的错误阻止预编译过程完成。一旦我解决了这个问题,svg 就被缓存了,测试以正常速度成功。
tldr:
如果您遇到此问题,请尝试运行 public/assets/.sprockets-manifest
以查看是否存在一些问题。如果该命令失败(例如,由于某些本地 rails assets:precompile
的问题,就像我的情况一样),那可能是 a) 阻止您的资产被缓存,以及 b) 由于失败的预编译命令而减慢您的测试速度比下一个完成需要更长的时间。