【发布时间】:2013-08-10 17:17:09
【问题描述】:
我已经开始学习在我的 Rails 应用程序中进行测试,并且正在使用 rSpec 和 Shoulda。
我有以下有效的测试:
it { should respond_to(:park_name) }
但是,我不明白的是,这是在运行什么?这是在模型本身还是模型的实例上运行,如果它是模型的实例,那么它会自动使用我的 Factory Girl 工厂吗?
对这里实际发生的事情有任何简单的解释吗?
更新:
好的,我有这个:
describe 'validations' do
subject { FactoryGirl.build(:coaster) }
it { should validate_presence_of(:name) }
it { should validate_presence_of(:speed) }
it { should validate_presence_of(:height) }
end
但是测试失败了。有什么想法吗?
Coaster.rb:
class Coaster < ActiveRecord::Base
extend FriendlyId
friendly_id :slug, use: :slugged
belongs_to :park
belongs_to :manufacturer
attr_accessible :name,
:height,
:speed,
:length,
:inversions,
:material,
:lat,
:lng,
:park_id,
:notes,
:manufacturer_id,
:style,
:covering,
:ride_style,
:model,
:layout,
:dates_ridden,
:times_ridden,
:order,
:on_ride_photo
scope :by_name_asc, lambda {
order("name ASC")
}
scope :made_from, lambda { |material|
where("material = ?", material)
}
scope :wooden, lambda {
made_from "wood"
}
scope :steel, lambda {
made_from "steel"
}
delegate :name, :location_1, :location_2, :location_3, :location_4,
to: :park,
allow_nil: true,
prefix: true
delegate :name, :url,
to: :manufacturer,
prefix: true
validates :name,
:presence => true
validates :height,
allow_nil: true,
numericality: {greater_than: 0}
validates :speed,
allow_nil: true,
numericality: {greater_than: 0}
validates :length,
allow_nil: true,
numericality: {greater_than: 0}
测试结果:
1) 过山车验证需要设置速度 失败/错误:它 { 应该 validate_presence_of(:speed) } 当速度设置为零时,预期的错误包括“不能为空白”,没有错误 # ./spec/models/coaster_spec.rb:75:in `block (3 levels) in '
2) 过山车验证应要求设置高度 失败/错误:它 { 应该 validate_presence_of(:height) } 当高度设置为零时,预期的错误包括“不能为空白”,没有错误 # ./spec/models/coaster_spec.rb:76:in `block (3 levels) in '
类似问题:
我有这个测试:
describe 'methods' do
subject { FactoryGirl.build(:coaster) }
it "should return a formatted string of coaster name at park name" do
name_and_park.should eq('Nemesis at Alton Towers')
end
end
Coaster.rb:
def name_and_park
[name, park.name].join (' at ')
end
运行测试时出错:
2) 过山车方法应该返回一个格式化的过山车名称字符串 公园名称 失败/错误:name_and_park.should eq('Nemesis at Alton Towers') 名称错误: '
中未定义的局部变量或方法name_and_park' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_6:0x007f84f4161798> # ./spec/models/coaster_spec.rb:111:inblock(3 级)
它说 name_and_park 不能被调用,但肯定应该在主题行中创建的 Coaster 实例上调用该方法?没有?
【问题讨论】:
-
这是与您之前提到的测试不同的三种测试。你之前的问题现在回答了吗?该测试现在通过了吗?
-
要回答这个关于
validate_presence_of结果的新问题,查看您的模型和测试结果会有所帮助。 -
respond_to 问题只是我不了解每条测试线正在运行的一个例子。立即将模型和测试结果添加到 OP。
标签: ruby-on-rails testing rspec factory-bot shoulda