[英]rspec - how to test for a model attribute that is not a database column
I have an Active Record based model:- House 我有一个基于Active Record的模型: - House
It has various attributes, but no formal_name
attribute. 它具有各种属性,但没有
formal_name
属性。 However it does have a method for formal_name
, ie 但它确实有一个
formal_name
的方法,即
def formal_name
"Formal #{self.other_model.name}"
end
How can I test that this method exists? 如何测试此方法是否存在?
I have: 我有:
describe "check the name " do
@report_set = FactoryGirl.create :report_set
subject { @report_set }
its(:formal_name) { should == "this_should_fail" }
end
But I get undefined method 'formal_name' for nil:NilClass
但我得到
undefined method 'formal_name' for nil:NilClass
First you probably want to make sure your factory is doing a good job creating report_set -- Maybe put factory_girl under both development and test group in your Gemfile, fire up irb to make sure that FactoryGirl.create :report_set
does not return nil. 首先,您可能希望确保您的工厂在创建report_set方面做得很好 - 可能将factory_girl放在Gemfile中的开发和测试组下,启动irb以确保
FactoryGirl.create :report_set
不返回nil。
Then try 然后试试
describe "#formal_name" do
let(:report_set) { FactoryGirl.create :report_set }
it 'responses to formal_name' do
report_set.should respond_to(:formal_name)
end
it 'checks the name' do
report_set.formal_name.should == 'whatever it should be'
end
end
Personally, I'm not a fan of the shortcut rspec syntax you're using. 就个人而言,我不是你正在使用的快捷方式rspec语法的粉丝。 I would do it like this
我会这样做的
describe '#formal_name' do
it 'responds to formal_name' do
report_set = FactoryGirl.create :report_set
report_set.formal_name.should == 'formal_name'
end
end
I think it's much easier to understand this way. 我认为这样理解起来要容易得多。
# model - make sure migration is run so it's in your database class Video < ActiveRecord::Base # virtual attribute - no table in db corresponding to this def embed_url 'embedded' end end # factory FactoryGirl.define do factory :video do end end # rspec require 'spec_helper' describe Video do describe '#embed_url' do it 'responds' do v = FactoryGirl.create(:video) v.embed_url.should == 'embedded' end end end $ rspec spec/models/video_spec.rb # -> passing test
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.