Sri*_*Sri 8 rspec ruby-on-rails shoulda rspec-rails ruby-on-rails-3
我的模型中有一个私有方法,如下所示:
validate :record_uniq
private
def record_uniq
if record_already_exists?
errors.add(:base, "already exists")
end
end
def record_already_exists?
question_id = measure.question_id
self.class.joins(:measure).
where(measures: {question_id: ques_id}).
where(package_id: pack_id).
exists?
end
Run Code Online (Sandbox Code Playgroud)
这种方法更像是uniqueness
防范重复记录的范围.我想知道如何validate :record_uniq
使用shoulda
或编写测试 rspec
?
describe Foo do
before do
@bar = Foo.new(enr_rds_measure_id: 1, enr_rds_package_id: 2)
end
subject { @bar }
it { should validate_uniqueness_of(:record_uniq) }
end
Run Code Online (Sandbox Code Playgroud)
简单 - 构建一个未通过验证的对象,验证它并验证是否已设置正确的错误消息.
例如(如果您有一个名为City的模型):
it 'validates that city is unique' do
city = City.new # add in stuff to make sure it will trip your validation
city.valid?
city.should have(1).error_on(:base) # or
city.errors(:base).should eq ["already exists"]
end
Run Code Online (Sandbox Code Playgroud)
小智 7
这是我将使用RSpec 3语法做的事情.
it 'validates that city is unique' do
city = City.new('already taken name')
expect(city).to be_invalid
expect(city.errors[:base]).to include('already exists')
end
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6629 次 |
最近记录: |