0

使用 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

我已经标记了这篇文章mockingstubbing因为我从来没有有意识地使用过这两种技术,但我认为其中一种技术可能会给出答案。

4

1 回答 1

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
于 2013-06-16T15:54:19.993 回答