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

我是铁杆上的新手,我必须用’Rspec’,’shoulda’和’factory girl’gem为现有的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 ' 

当试图分配像这样的值@ brief.brand_info =’bla bla bla’

要检查它是否已保存:

 @brief.save.should be_true 

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

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

 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