[英]mocking/stubbing a controller recaptcha method with rspec in rails
[英]Rspec, stubbing the presence of an object in a Rails application controller
我的應用程序控制器中有一個方法“ get_location_details”,在找到場所之后,每次操作之前都會調用該方法。 看起來像這樣
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
我想開始測試我。 輸出; ii。 上下文(即不存在場所)。 我認為,為了實現這一目標,我需要保留場地的存在,而我似乎無法弄清楚該怎么做。
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
但是我的測試一直失敗
undefined method `facility_with_opening_hours' for nil:NilClass
這表明該場所沒有存根。 我如何存根場地? 我在這里做錯了什么? 我經常參加應用程序控制器測試,但是我想掌握一下。 如果有人可以推薦任何進一步的閱讀,將不勝感激。
非常感謝
我不確定您是否可以輕易在rspec中存根成員。 您可以為成員設置一個值,或者(最好)重構代碼以從getter而不是成員中讀取值:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.