fixed with defining File.expand_path(Rails.root) as application-wide environment-dependant constant, and modifying it for test environment.
stubbing File.expand_path in rspec/rails 4
-
30-06-2022 - |
Domanda
i have multiple calls to File.expand_path(Rails.root) in my code
for testing i created following configuration in spec/support
RSpec.configure do |config|
config.before(:each) do
File.stub(:expand_path).and_return("spec/fs")
end
end
so that instead of "/home/user/" each request to File.expand_path returns "spec/fs/"
it worked well while i was on rails 3
however after moving to rails 4, tests started throwing following error:
Failure/Error: let(:category) { build(:category) }
LoadError:
cannot load such file -- spec/fs
why does it appear/how can i fix that?
ps.
tests/models are very basic, but strangely this test case fails:
#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
but this one doesn't!
#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
category factory being as simple as:
FactoryGirl.define do
factory :category do
name "TestCategory"
end
end
built with simple
let(:category) { build(:category) }
however it seems like stub failure occurs just while building the :category factory
Soluzione 2
Altri suggerimenti
File.expand_path
is a very commonly used method. I would not be surprised if the Rails, RSpec or FactoryGirl software relied on it as part of their code which gets executed after the double is put in place (e.g. to load the Category
model code). You could easily verify that by printing a stack trace or going to the debugger when it gets invoked and seeing where you are.