I have an action in my controller that loads up an instance variable with an instance of an object from an API I have no control over:
def index
@obj = MyObj.find(id: params[:id])
end
MyObj.find makes an API call and returns me what that API returns.
Now say I want to write a test for my view, but I can't use a test database since my app is dependant on that API. I can never count on the API returning me a testable object and some of the tests I want to try are dependant on the state of that object.
I would like to be able to, before rendering my view, create my own test @obj manually and have my tests work on a view render informed by that @obj.
Ideally it would be something like this:
before(:all) do
@obj = {attr1: "abc", attr2: 123}
driver.navigate.to("#{ENV['RAILS_HOST']}/my_view/123")
end
Which clearly doesn't work. Is there some way to do this?
EDIT: Trying to stub the method doesn't seem to work, here's how it currently looks:
Spec:
before(:each) do
allow(Library::Equipment)
.to receive(:mymethod)
.with(123)
.and_return("Stub method")
puts Library::Equipment.mymethod(123)
#prints "Stub method"
driver.navigate.to("#{ENV['RAILS_HOST']}/library/equipments/123/variables")
end
/library/equipments/:equipment_id/variables routes to library/variables#index, which looks like this:
def index
@test = Library::Equipment.mymethod(123)
puts @test
#prints "Real method"
# other code...
end
My Library::Equipment class has this class method:
def self.mymethod(param)
"Real method"
end
And within my index.html.erb I simply have <%= @test %> to see what it contains. As you can see, the return of mymethod differs when called from my spec file and from my index action
RSpec::Mocks.with_temporary_scopewill allow you to use stubbing in abefore(all)but the stubbing will be removed when the scope ends. Please remove thewith_temporary_scopeAND changebefore(:all)tobefore(:each)/beforeat the same time.