使用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?
true
时的测试用例,以及false
时的测试用例。
但是我不想写代码行创建@input
,在别处设置其他值以确保为@survey
等选择@input,只是为了设置{ {1}}为真。有什么方法可以做我喜欢的事情:
@survey.selected_input.present?
我已对此帖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
进行了标记,因为我从未有意识地使用这两种技术,但我认为其中一种可能会得到答案。
答案 0 :(得分:0)
一般来说,对于被测对象的存根方法并不是一个好主意。但是,既然您询问了语法,那么您要找的是RSpec Mocks:
describe Survey do
subject(:survey) { Survey.new(...) }
context 'requesting the description' do
it 'contains product name when it has input' do
survey.stub(selected_input: 'apples')
expect(survey.description).to eq "How's them apples?"
end
end
end