RSPEC以电子邮件格式失败

时间:2013-02-12 15:56:15

标签: ruby-on-rails rspec

我一直在浏览Rails教程,将用户帐户和运行测试放在一起,用于我正在进行的项目。

Failures:

  1) when email format is invalid should be invalid
     Failure/Error: @user.email = invalid_address
     NoMethodError:
       undefined method `email=' for nil:NilClass
     # ./spec/models/user_spec.rb:71:in `block (3 levels) in <top (required)>'
     # ./spec/models/user_spec.rb:70:in `each'
     # ./spec/models/user_spec.rb:70:in `block (2 levels) in <top (required)>'

  2) when email format is valid should be valid
     Failure/Error: @user.email = valid_address
     NoMethodError:
       undefined method `email=' for nil:NilClass
     # ./spec/models/user_spec.rb:81:in `block (3 levels) in <top (required)>'
     # ./spec/models/user_spec.rb:80:in `each'
     # ./spec/models/user_spec.rb:80:in `block (2 levels) in <top (required)>'

Finished in 0.527 seconds
9 examples, 2 failures

Failed examples:

rspec ./spec/models/user_spec.rb:67 # when email format is invalid should be invalid
rspec ./spec/models/user_spec.rb:78 # when email format is valid should be valid

我不知道问题是什么。我看到了它的内容,但我甚至将C&amp; P中的代码用来仔细检查我做了什么以确保所有内容都正确输入。

这是user_spec文件。

https://gist.github.com/pwz2k/4770845

这是user.rb文件。

https://gist.github.com/pwz2k/4770854

直到我添加了电子邮件验证后才显示失败。

2 个答案:

答案 0 :(得分:0)

确保在开始测试之前创建@user ..你的用户测试中是否有这些行? (rails tutorial listing 6.16

before do
    @user = User.new(name: "Example User", email: "user@example.com")
end

答案 1 :(得分:0)

错误很明显!你正在设置电子邮件到零级。这意味着您应该将电子邮件设置为我们说的用户

 @user.email = "something"

错误是抱怨没有用户,并且没有任何用户的电子邮件。

在这里工作是一个示例代码,可以帮助您解决这个问题。

 describe "validations" do
   before(:each) do
     @user = User.new(name: "gates", email: "somename@gmail.com")
   end
   it "should be invalid" do
     invalid_emails = %w{gs@gmail p.com name.gmail.com foo.ymail}
     invalid_emails.each do |invalid_email|
       @user.email = invalid_email
       expect(@user.email).to_not be_valid
    end
   end

   it "should be valid" do
    @user.name = "somename"
    valid_emails = %w{user@foo.COM A_US-ER@f.b.org frst.lst@foo.jp 
    a+b@baz.cn}
    valid_emails.each do |valid_email|
     @user.email = valid_email
     expect(@user.email).to be_valid
    end
   end  
 end

请确保您已在fixures文件夹中为用户创建了一个修复程序。

希望这有帮助!