问题
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?
This is the brief models code:
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. :)
Failures:
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)>'
when try to assign value like this @brief.brand_info = 'bla bla bla'
回答1:
To check if it is saved:
@brief.save.should be_true
Saving forces validation. If validation fails, save doesn't occur, in which case it returns false.
回答2:
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
来源:https://stackoverflow.com/questions/12023470/how-to-test-a-method-of-models-with-rspec-and-factory