我在rails 5中有小应用程序。我尝试使用Rspec来测试它,但只读模型失败。Rspec测试只读模型
我只读模型产品和正常模型ProductMsp。第二个是与产品关联的所有价格列表,并存储在Rails数据库中。产品是与另一个数据库的外部只读连接,用于撤销产品列表。
我添加了关联到spec/factories/product_msps.rb的产品。
FactoryGirl.define do
factory :product_msp do
product_id 11
initial_date '01-01-2017'
expiry_date '31-01-2017'
msp 9999.99
association :product
end
end
我没有添加任何新的测试。当我再次运行rspec时,我得到失败。可能rspec想创建产品,但不能由于只读数据库表。
Failures:
1) ProductMsp Validations initial_date cannot by empty
Failure/Error: pm = FactoryGirl.build(:product_msp, initial_date: nil)
ActiveRecord::ReadOnlyRecord:
Product is marked as readonly
# ./spec/models/product_msp_spec.rb:17:in `block (3 levels) in <top (required)>'
下面是失败的测试:(有更多的失败)
require 'rails_helper'
RSpec.describe ProductMsp, type: :model do
it 'initial_date cannot by empty' do
pm = FactoryGirl.build(:product_msp, initial_date: nil)
pm.valid?
expect(pm.errors[:initial_date]).to include("can't be blank")
end
end
规格/工厂/ products.rb
FactoryGirl.define do
factory :product do
id 11
name 'Porsche Cayenne'
end
end
和应用程序/模型/ product.rb
class Product < ApplicationRecord
self.primary_key = 'tw_Id'
def readonly?
true
end
has_many :product_msps
default_scope {where(product_type:1).order(:name)}
一个主要问题是:如何处理测试和只读模型?
rspec适合它吗?
我应该摆脱测试的只读模式
我通过互联网搜索,但我没有发现这样的问题的任何实例。我需要在另一个数据库之上构建应用程序,但我希望以某种方式进行测试。 :-)
您是否尝试将'skip_create'添加到您的'product'工厂?我想它应该有所帮助 – Ngoral
非常感谢您的帮助。这很容易。我专注于rspec,但解决方案不在那里。 – rpeczykowski