使用 Rspec,我正在为 @survey.description 编写单元测试:
class Survey < ActiveRecord::Base
def description
if self.question.try(:description).present? && self.selected_input.present?
return self.question.try(:description).gsub("{{product-name}}", self.selected_input.name)
else
return self.question.try(:description)
end
end
def selected_input
@matches = Input.all.select{|input| self.goods.to_a.matches(input.goods) && self.industries.to_a.matches(input.industries) && self.markets.to_a.matches(input.markets)}
@selection = @matches.select{|input| input.in_stock(self.competitor) == true}
if @selection.empty? || @selection.count < self.iteration || @selection[self.iteration-1].try(:name).nil?
return false
else
return @selection[self.iteration-1]
end
end
end
@survey.selected_input.present?
至少,我想为 when istrue
和 when it is编写一个测试用例false
。
但我不想逐行编写代码创建一个@input
,在其他地方设置其他值以确保为@survey
等选择@input,只是为了设置@survey.selected_input.present?
为 true。有没有办法我可以做类似的事情:
describe "description" do
it "should do something when there is a selected input" do
just_pretend_that @survey.selected_input = "apples"
@survey.description.should == "How's them apples?"
end
end
我已经标记了这篇文章mocking
,stubbing
因为我从来没有有意识地使用过这两种技术,但我认为其中一种技术可能会给出答案。