带设计的 RSpec [英] RSpec with devise

查看:61
本文介绍了带设计的 RSpec的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚接触 Rails :)我正在尝试运行我的第一个测试.为什么这个测试通过?用户名应该至少有 2 个字符,我的用户名有更多,但它仍然通过了测试.

im new to rails :) im trying to run my first test. why does this test pass? username should have at least 2 characters, my username has more and it still passes test.

user.rb:

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

user_spec.rb

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

推荐答案

这一行:

it { should_not be_valid }

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

Uses the implicit subject. RSpec automatically creates an instance of the class User that you can then use implicitly within an it block. But your test then creates another instance and assigns it to @user -- the two instances are not the same.

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

If you want to use the implicit subject, you can do:

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

这篇关于带设计的 RSpec的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆