问题描述
我是Rails的新手,我必须使用'Rspec','shoulda'和'factory girl'宝石为现有的rails应用程序编写测试.我可以测试非特定的测试,例如validates_presence_of:带有'sholda'匹配器的测试.但是我想测试模型中的方法.我可以想象我需要做的事情,但我不能作文.
I'm newbie on rails and I have to write tests for existing rails apps with 'Rspec','shoulda' and 'factory girl' gems. I can test non specific tests like validates_presence_of: something with 'sholda' matchers. But I want to test methods which in models. I can visualize what I need to do, but I can't compose.
这是我正在谈论的示例:
This is an example what I'm talking about:
.
.
.
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
.
.
.
我要测试的是这段代码中的简短可编辑内容.我该如何测试?
I want to test is brief editable in this code. How can I test it?
这是简短的模型代码:
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
如果我能找到一个起点,我将非常高兴.感谢帮助. :)
I will be very happy if I can find a starting point. Thanks for help. :)
失败:
1)如果项目不是以可编辑的摘要开始的,则摘要是可编辑的.
1) Brief is editable if project is not started with editable brief.
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'
when try to assign value like this @brief.brand_info = 'bla bla bla'
推荐答案
我自己找到了解决此问题的方法.
I found a solution for this problem by myself.
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
这篇关于如何使用rspec和factory测试模型的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!