【问题标题】:RSpec with deviseRSpec 与设计
【发布时间】:2013-03-04 19:12:05
【问题描述】:

我是 Rails 新手 :) 我试图运行我的第一个测试。为什么这个测试会通过?用户名应该至少有 2 个字符,我的用户名有更多并且仍然通过测试。

user.rb:

validates :username, :length => { :minimum => 2 }

user_spec.rb

require 'spec_helper'

describe User do

before do
  @user = User.new(username: "Example User", email: "user@example.com",
                   password: "foobar", password_confirmation: "foobar")
end

describe "when name is not present" do
  before { @user.username="aaaahfghg" }
  it { should_not be_valid }   end

end

【问题讨论】:

  • 我没有看到用户名长度的测试。验证也是最小 2 的任何超过 2 的将通过验证。

标签: ruby-on-rails ruby-on-rails-3 rspec-rails


【解决方案1】:
describe "when name is not present" do
 before {  @user.username = "aaaahfghg" }
 it { should_not be_valid }   
end

首先,您的描述块正在测试错误的内容。如果您想测试“名称不存在”,您应该设置:

@user.username = "" #使用户名为空。

但是,为了检查用户名是否为空,您应该添加 validates :username, presence: true 。虽然您可能不需要它,因为您有 { minimum: 2 } 验证

现在,@user.username = "aaaahf" # 更好的写法是 'a' * 5 例如,它创建一个由 5 a's = aaaaa 组成的字符串。

这表示您的用户名超过 2 个字符,因此您的验证很好,{ minimum: 2 } 测试应该通过。

如果您想确保用户名超过 2 个字符,那么

@user.username = 'a'

希望有所帮助。

【讨论】:

    【解决方案2】:

    这一行:

    it { should_not be_valid }
    

    使用implicit subject。 RSpec 自动创建User 类的实例,然后您可以在it 块中隐式使用该实例。但是您的测试随后会创建另一个实例并将其分配给@user——这两个实例并不相同。

    如果你想使用隐式主语,你可以这样做:

    subject { User.new(args) }
    before {  subject.username = "aaaahfghg" }
    it { should_not be_valid }   
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-09
      • 1970-01-01
      • 1970-01-01
      • 2017-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多