我已经开始在我的 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
但是测试失败了。有任何想法吗?
过山车.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) } 当速度设置为 nil 时,预期的错误包括“不能为空白”,没有错误 # ./spec/models /coaster_spec.rb:75:in `block (3 levels) in '
2) 过山车验证应该要求设置高度失败/错误:它 { 应该 validate_presence_of(:height) } 当高度设置为 nil 时,预期的错误包括“不能为空白”,没有错误 # ./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
过山车.rb:
def name_and_park
[name, park.name].join (' at ')
end
运行测试时出错:
2) 过山车方法应在公园名称故障/错误处返回格式化的过山车名称字符串:name_and_park.should eq('Nemesis at Alton Towers') NameError: undefined local variable or method
name_and_park' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_6:0x007f84f4161798> # ./spec/models/coaster_spec.rb:111:in
block (3 levels) in '
它说 name_and_park 不能被调用,但肯定应该在主题行中创建的 Coaster 实例上调用该方法?不?