我有一个基于环境变量ENV‘’APP_FOR‘的不同验证的用户模型。这可以是"app-1“或"app-2”。app-1验证用户名,而app-2验证电子邮件地址。下面是我的应用程序1的用户模型规范:
require 'rails_helper'
RSpec.describe User, type: :model do
include Shared::Categories
before do
ENV['APP_FOR']='app-1'
end
context "given a valid User" do
before { allow_any_instance_of(User).to receive(:older_than_18?).and_return(true) }
it {should validate_presence_of :username}
end
end
这是app-2的用户模型规范。
require 'rails_helper'
RSpec.describe User, type: :model do
include Shared::Categories
before do
ENV['APP_FOR']='app-2'
end
context "given a valid User" do
before { allow_any_instance_of(User).to receive(:older_than_18?).and_return(true) }
it {should validate_presence_of :email}
end
end
我的问题是,环境变量并没有像我所期望的那样被设置在前置块中。对怎么做有什么想法吗?
编辑1
这是我的验证实现。我使用了一个关注点来扩展用户模型:
module TopDogCore::Concerns::UserValidations
extend ActiveSupport::Concern
included do
if ENV['APP_FOR'] == 'app-1'
validates :username,
presence: true,
uniqueness: true
elsif ENV['APP_FOR'] == 'app-2'
validates :email,
presence: true,
uniqueness: true
end
end
end
发布于 2016-01-27 12:40:11
试试看
module TopDogCore::Concerns::UserValidations
extend ActiveSupport::Concern
included do
validates :username,
presence: true,
uniqueness: true, if: -> { ENV['APP_FOR'] == 'app-1' }
validates :email,
presence: true,
uniqueness: true, if: -> { ENV['APP_FOR'] == 'app-2' }
end
end
发布于 2016-01-28 02:04:10
在示例中运行代码之前,RSpec将加载subject类。当你这样做时:
before do
ENV['APP_FOR'] = # ...
end
已经太迟了。类定义已经执行。您可以通过简单地从类定义中打印ENV['APP_FOR']
的值(在您的例子中是包含的关注点)来看到这一点。它是nil
,因为加载类源文件时没有设置环境变量。
使用lambda (正如这里所建议的)延迟评估应该是可行的。您可以尝试使用自己的测试,而不是shoulda_matchers
提供的测试,例如:
expect(subject.valid?).to be false
expect(subject.errors[:username].blank?).to be false
发布于 2016-01-27 14:07:25
https://stackoverflow.com/questions/35036867
复制相似问题