Ruby on rails rspec-如何测试不是数据库列的模型属性
我有一个基于活动记录的模型:-House 它有各种属性,但没有Ruby on rails rspec-如何测试不是数据库列的模型属性,ruby-on-rails,ruby,rspec,rspec-rails,expectations,Ruby On Rails,Ruby,Rspec,Rspec Rails,Expectations,我有一个基于活动记录的模型:-House 它有各种属性,但没有正式的\u name属性。 但是,它确实有一个方法用于正式名称,即 def formal_name "Formal #{self.other_model.name}" end 如何测试此方法是否存在 我有: describe "check the name " do @report_set = FactoryGirl.create :report_set subject { @report_set }
正式的\u 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
但是我得到了nil:NilClass的
未定义的方法'formal_name'
就我个人而言,我不喜欢你使用的快捷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
我认为这样理解要容易得多
编辑:Rails 3.2项目中FactoryGirl 2.5的完整工作示例。这是经过测试的代码
# 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
#model-确保迁移已运行,以便它位于数据库中
类视频通过测试
首先,您可能希望确保您的工厂在创建报告集方面做得很好——可能将factory\u girl放在GEM文件中的开发组和测试组之下,启动irb以确保FactoryGirl.create:report\u set
不会返回零
然后试试看
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
问题不是没有正式的名称,而是您的
@report\u集
是nil
。尝试将创建逻辑放在让{}
块中,我不会执行响应测试。此时,您正在测试ruby,这是没有必要的。但为了公平起见,作者确实问过这件事。这是我第一次写回复来测试TBH。我写它只是因为@michael durrant要求=我同意他的问题很可能不是方法的响应,而是他的工厂设置和/或定义。响应是唯一有效的部分。我确保respond to(:junk)不起作用,respond to(:name)起作用。这个简单的测试用于检查使用此格式或任何其他格式时无法使用的值。-1适用于ID(真实属性),但不适用于name(虚拟属性)。我得到了未定义的方法“name”@MichaelDurrant我使用的是factory girl 2.5和factory girl rails 1.6,它肯定能与虚拟属性一起工作。不知道为什么它不适合你。我正在添加一个完整的示例,其中包含经过测试的代码