[英]rspec - how to test for a model attribute that is not a database column
我有一个基于Active Record的模型: - House
它具有各种属性,但没有formal_name
属性。 但它确实有一个formal_name
的方法,即
def formal_name
"Formal #{self.other_model.name}"
end
如何测试此方法是否存在?
我有:
describe "check the name " do
@report_set = FactoryGirl.create :report_set
subject { @report_set }
its(:formal_name) { should == "this_should_fail" }
end
但我得到undefined method 'formal_name' for nil:NilClass
首先,您可能希望确保您的工厂在创建report_set方面做得很好 - 可能将factory_girl放在Gemfile中的开发和测试组下,启动irb以确保FactoryGirl.create :report_set
不返回nil。
然后试试
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
就个人而言,我不是你正在使用的快捷方式rspec语法的粉丝。 我会这样做的
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
我认为这样理解起来要容易得多。
# 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.