gpt4 book ai didi

ruby-on-rails - 重用 RSpec 行为验证

转载 作者:行者123 更新时间:2023-12-01 18:07:03 25 4
gpt4 key购买 nike

在我的 Rails 3 应用程序中,我有一个 RSpec 规范,用于检查给定字段(用户模型中的角色)的行为,以保证该值在有效值列表。

现在我将在另一个模型中为另一个字段提供完全相同的规范,并具有另一组有效值。我想提取公共(public)代码,而不是仅仅复制和粘贴它,更改变量。

我想知道使用共享示例或其他 RSpec 重用技术是否会出现这种情况。

以下是相关的 RSpec 代码:

describe "validation" do  
describe "#role" do
context "with a valid role value" do
it "is valid" do
User::ROLES.each do |role|
build(:user, :role => role).should be_valid
end
end
end

context "with an empty role" do
subject { build(:user, :role => nil) }

it "is invalid" do
subject.should_not be_valid
end

it "adds an error message for the role" do
subject.save.should be_false
subject.errors.messages[:role].first.should == "can't be blank"
end
end

context "with an invalid role value" do
subject { build(:user, :role => 'unknown') }

it "is invalid" do
subject.should_not be_valid
end

it "adds an error message for the role" do
subject.save.should be_false
subject.errors.messages[:role].first.should =~ /unknown isn't a valid role/
end
end
end
end

重用此代码的最佳情况是什么,但将 role (正在验证的字段)和 User::ROLES (有效值的集合)提取到参数传递给此代码?

最佳答案

我认为这是共享示例的一个完全合理的用例。例如像这样的东西:

shared_examples_for "attribute in collection" do |attr_name, valid_values|

context "with a valid role value" do
it "is valid" do
valid_values.each do |role|
build(:user, attr_name => role).should be_valid
end
end
end

context "with an empty #{attr_name}" do
subject { build(:user, attr_name => nil) }

it "is invalid" do
subject.should_not be_valid
end

it "adds an error message for the #{attr_name}" do
subject.save.should be_false
subject.errors.messages[attr_name].first.should == "can't be blank"
end
end

context "with an invalid #{attr_name} value" do
subject { build(:user, attr_name => 'unknown') }

it "is invalid" do
subject.should_not be_valid
end

it "adds an error message for the #{attr_name}" do
subject.save.should be_false
subject.errors.messages[attr_name].first.should =~ /unknown isn't a valid #{attr_name}/
end
end
end

然后你可以在你的规范中这样调用它:

describe "validation" do  
describe "#role" do
behaves_like "attribute in collection", :role, User::ROLES
end
end

尚未对此进行测试,但我认为它应该有效。

关于ruby-on-rails - 重用 RSpec 行为验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14004916/

25 4 0
文章推荐: perforce - p4sync,如何在使用通配符时排除文件?
文章推荐: java - 为列表中的特定元素设置 ValidationError 消息
文章推荐: java - Streams API::如何从 LIST 修改自定义对象的变量?