Using Rspec, I am writing unit tests for @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
At a minimum, I'd like to write a test case for when @survey.selected_input.present?
is true
and one for when it is false
.
But I don't want to write line upon line of code creating an @input
, setting other values elsewhere to ensure the @input is selected for the @survey
, etc etc, just to set @survey.selected_input.present?
to true. Is there some way I can do something like:
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
I've tagged this post mocking
and stubbing
as I've never consciously used either technique but I think one of them may hold the answer.