stubing File.expand_rspec/rails 4中的路径

stubing File.expand_rspec/rails 4中的路径,rspec,ruby-on-rails-4,factory-bot,stub,Rspec,Ruby On Rails 4,Factory Bot,Stub,我在代码中多次调用File.expand_path(Rails.root) 为了进行测试,我在spec/support中创建了以下配置 RSpec.configure do |config| config.before(:each) do File.stub(:expand_path).and_return("spec/fs") end end 因此,每个对File.expand_路径的请求都返回“spec/fs/,而不是“/home/user/” 当我在rails 3上时,它

我在代码中多次调用File.expand_path(Rails.root)

为了进行测试,我在spec/support中创建了以下配置

RSpec.configure do |config|
  config.before(:each) do
    File.stub(:expand_path).and_return("spec/fs")
  end
end
因此,每个对File.expand_路径的请求都返回“spec/fs/,而不是“/home/user/”

当我在rails 3上时,它工作得很好

但是,在移动到rails 4之后,测试开始抛出以下错误:

 Failure/Error: let(:category) { build(:category) }
 LoadError:
   cannot load such file -- spec/fs
为什么会出现这种情况/我如何解决

附言

测试/模型非常基本,但奇怪的是,这个测试用例失败了:

#in class
def first method(category)
  "#{File.expand_path(Rails.root)}/public/collections/#{self.name}/_new/#{category.name.downcase}"
end

#in rspec
describe "#first_method" do
  it { expect(collection.first_method(category)).to be_instance_of(String) }
end
但是这个不行

#in class
def second_method
  "#{File.expand_path(Rails.root)}/public/collections/#{self.name}/_new/"
end

#in rspec
describe "#second_method" do
  it { expect(collection.second_method).to be_instance_of(String) }
end
类别工厂简单如下:

FactoryGirl.define do
  factory :category do
    name "TestCategory"
  end
end
用简单的

let(:category) { build(:category) }

然而,似乎存根失败发生在构建:category工厂文件时。expand_path是一种非常常用的方法。如果Rails、RSpec或FactoryGirl软件将其作为其代码的一部分,并在安装double后执行(例如加载
类别
模型代码),我不会感到惊讶。您可以通过打印堆栈跟踪或在调用调试器时转到调试器并查看您所在的位置来轻松验证这一点。

修复了将File.expand_path(Rails.root)定义为应用程序范围的依赖于环境的常量,并为测试环境修改它