[英]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.