I have a method 'get_location_details' in my application controller which is called after the venue is found, before every action. It looks like this,
def get_venue
@venue = Venue.friendly.find(params[:venue_id])
end
def get_location_details
@venue_information = {
opening_times: @venue.facility_with_opening_hours.any? ? venue.facility_with_opening_hours.first.opening_times_for_week(Date.today) : '',
location: {address1: venue.address1,
address2: venue.address2,
town: venue.town,
county: venue.county,
postcode: venue.postcode},
contact: {email: venue.email,
telephone: venue.telephone},
social: {facebook: venue.facebook,
twitter: venue.twitter}
}
end
I want to begin testing i. the output, ii. context's (ie. where a venue isn't present). I assume that in order to achieve this i need to stub the presence of the venue, which is what I cant seem to figure out how to do.
describe "get_location_details" do
before do
test_hash = [{:day=>"Mon - Fri", :open=>"2001-01-01 06:30:00 +0000", :close=>"2001-01-01 22:00:00 +0000", :closed=>false},
{:day=>"Sat", :open=>"2001-01-01 08:00:00 +0000", :close=>"2001-01-01 19:00:00 +0000", :closed=>false},
{:day=>"Sun", :open=>"2001-01-01 08:00:00 +0000", :close=>"2001-01-01 17:00:00 +0000", :closed=>false}]
allow(controller).to receive(:venue).and_return(venue)
allow(venue).to receive(:facility_with_opening_hours).and_return(test_hash)
end
it "returns http success" do
expect(controller.send(:get_location_details).is_a?(Hash)).to be_truthy
end
end
However my test keeps failing with
undefined method `facility_with_opening_hours' for nil:NilClass
which indicates the venue isn't being stubbed. How can i stub the venue? What am I doing wrong here? I often trip up on application controller testing, but I want to get to grips with it. If anyone can recommend any further reading that would be greatly appreciated.
Many Thanks
I'm not sure you can easily stub a member in rspec. You can either set the member with a value, or (preferably) refactor your code to read the value from a getter rather than a member:
def venue
@venue ||= Venue.friendly.find(params[:venue_id])
end
def location_details
@venue_information ||= {
opening_times: venue.facility_with_opening_hours.any? ? venue.facility_with_opening_hours.first.opening_times_for_week(Date.today) : '',
location: {address1: venue.address1,
address2: venue.address2,
town: venue.town,
county: venue.county,
postcode: venue.postcode},
contact: {email: venue.email,
telephone: venue.telephone},
social: {facebook: venue.facebook,
twitter: venue.twitter}
}
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.