如何存根此属性?
user.rb
def my_method
scheduling_frequency_minutes = self.business.settings_group.scheduling_frequency.minutes
# where scheduling_frequency is an integer field in the settings_group model
# but this is still set to the default (60), not 30
end
user_spec.rb
it "get available time slots (on the half hour)" do
# 1st attempt:
@business.settings_group.scheduling_frequency = 30
# where @business is the same Business pointed to by 'self.business' in the user.rb model
# 2nd attempt:
#Business.stub_chain(:settings_group, :scheduling_frequency).and_return(30)
#3rd attempt:
settings_group = mock("settings_group")
settings_group.stub(:scheduling_frequency).and_return(30)
@business.should_receive(:settings_group).and_return(settings_group)
@business.users.all.first.my_method
end
更新
这是我的最新尝试,但仍然无法运作。发生了什么?
user = @business.users.all.first
user.stub_chain(:business, :settings_group, :scheduling_frequency).and_return(30)
user.my_method()
-
def my_method
debugger
# p self.business.settings_group.scheduling_frequency -> 60
end
答案 0 :(得分:2)
您需要在整个方式和正确的上下文中链接(在本例中为用户)
user = User.new
user.stub_chain(:business, :settings_group, :scheduling_frequency).and_return(30)
user.my_method
我尝试了以下独立版本并且有效。 (我在rails之外做了这个,所以分钟方法不可用。)
require 'rspec'
class User
def my_method
scheduling_frequency_minutes = self.business.settings_group.scheduling_frequency
end
end
describe User do
it "get available time slots (on the half hour)" do
user = User.new
user.stub_chain(:business, :settings_group, :scheduling_frequency).and_return(30)
user.my_method.should eql(30)
end
end