如何使用rspec和factory测试模型的方法

时间:2012-08-19 01:14:35

标签: ruby-on-rails testing rspec factory-bot shoulda

我是铁杆上的新手,我必须用'Rspec','shoulda'和'factory girl'宝石为现有的rails应用程序编写测试。我可以测试非特定的测试,例如validates_presence_of:带有'sholda'匹配器的东西。但我想测试模型中的方法。我可以想象我需要做什么,但我不能写作。

这就是我所说的一个例子:

.
.
.
context 'is editable if project is not started' do
  setup do
    @brief=Factory(:brief)
    @started_project=Factory(:project_started, :brief => @brief)
    @brief_have_no_project=Factory(:brief)
  end
  specify "with editable brief" do
    @brief.brand_info = 'bla bla bla' #change brand info, this is impossible
    #i can't compose this section :S
  end
  specify "with non-editable brief" do

  end
end

.
.
.

我想在此代码中进行简单的可编辑测试。我该怎么测试呢?

这是简要的型号代码:

class Brief < ActiveRecord::Base
  belongs_to :project
  validate :can_only_be_edited_if_project_is_not_started

  .
  .
  .

  def can_only_be_edited_if_project_is_not_started
    errors.add(:project_id, 'can_only_be_edited_if_project_is_not_started') if
      !project.nil? && !project.brief_can_be_edited?
  end

  .
  .
  .

end
如果我能找到一个起点,我将非常高兴。感谢帮助。 :)

故障:

1)如果项目未以可编辑的简短启动,则可以编辑简介。

Failure/Error: @brief.brand_info = 'bla bla bla'
 NoMethodError:
   undefined method `brand_info=' for nil:NilClass
 # ./spec/models/brief_spec.rb:34:in `block (3 levels) in <top (required)>'

当尝试分配像这样的值@ brief.brand_info ='bla bla bla'

2 个答案:

答案 0 :(得分:0)

检查是否已保存:

@brief.save.should be_true

省力验证。如果验证失败,则不会进行保存,在这种情况下,它将返回false。

答案 1 :(得分:0)

我自己找到了解决这个问题的方法。

it "with editable brief (not started project)" do
  brief=Factory.build(:brief)
  Factory(:project, :brief => brief)
  brief.should have(0).error_on(:project_id)
end
it "with editable brief (nil project)" do
  brief=Factory.build(:brief)
  brief.brand_info="bla bla bla"
  brief.should have(0).error_on(:project_id)
end
it "with non-editable brief" do
  brief=Factory.build(:brief)
  Factory(:project_started, :brief => brief)
  brief.should have(1).error_on(:project_id)
end