我有一个在创建时运行的自定义验证。
validate :validate_emails, if: :send_email, on: :create
在我的规范中,我这样做。
describe "#validate_emails" do
let(:box_shared_link_2) { BoxSharedLink.new(box_file, link_type: "view", email: "[email protected] [email protected];[email protected]") }
let(:invalid_box_shared_link) { BoxSharedLink.new(box_file, link_type: "view", email: "john jane;[email protected]", send_email: "Update and Send Link") }
it "should be invalid" do
expect(invalid_box_shared_link).to_not be_valid
end
it "should be valid" do
expect(box_shared_link_2).to be_valid
end
end
我如何告诉RSpec在创建时运行验证?谢谢你
你可能知道这个,但是 be_foo
匹配器调用 foo?
的方法,并检查其真实性,所以。
it "should be invalid" do
expect(invalid_box_shared_link).to_not be_valid
end
只会叫 valid?
因为它不会触发对象的创建--你的验证不会被触发。
你需要做的是这样的事情。
it "should be invalid" do
expect(invalid_box_shared_link.save).to eq(false) # saving failed
expect(invalid_box_shared_ling.errors).not_to be_empty # saving failed because of validation errors
# you might also want to check the actual error, like
expect(invalid_box_shared_ling.errors).to include(emails: 'validation error message') # I'm guessing what actually the array would include
end