gpt4 book ai didi

ruby-on-rails - 如何覆盖从内部引用的常量为 RSpec 验证

转载 作者:行者123 更新时间:2023-12-03 23:56:39 24 4
gpt4 key购买 nike

我的模型有这样的自定义验证。

class User
# skip before

MAX_FILE_SIZE = 10.megabytes.to_i
validates :file, size: { max: MAX_FILE_SIZE }

# skip after
end

而且,我想测试一下 MAX_FILE_SIZE通过覆盖 MAX_FILE_SIZE在规范。所以,我是这样写的。
context "MAX_FILE_SIZE is default" do
it do
# test something
end
end
context "MAX_FILE_SIZE is 1byte" do
before do
stub_const "User::MAX_FILE_SIZE", 1.bytes.to_i
end
it do
# test something
end
end

第一次测试通过。但是,由于 MAX_FILE_SIZE 未更改,第二次测试失败。

你能告诉我为什么吗?以及如何解决这种情况。

最佳答案

文档说示例运行后常量值会重置 https://relishapp.com/rspec/rspec-mocks/v/2-11/docs/stubbing-constants/stub-defined-constant

您是否尝试在示例中 stub 常量?

context "MAX_FILE_SIZE is 1byte" do
it do
stub_const "User::MAX_FILE_SIZE", 1.bytes.to_i
# test something
end
end

关于ruby-on-rails - 如何覆盖从内部引用的常量为 RSpec 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45180293/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com