【问题标题】:Devise, rspec and Mongoid test failing设计、rspec 和 Mongoid 测试失败
【发布时间】:2012-02-15 13:45:42
【问题描述】:
require 'spec_helper'

describe User do

  before(:each) do
    @attr = {
      :username => "User",
      :email => "aaaaer@example.com",
      :password => "foobar",
      :password_confirmation => "foobar",
      :phone_no => "0808322222"
    }
  end

  it "should create a new instance given a valid attribute" do
    User.create!(@attr)
  end
end

测试一直失败,不知道为什么

Failures:

  1) User should create a new instance given a valid attribute
     Failure/Error: User.create!(@attr)
     Mongoid::Errors::Validations:
       Validation failed - Phone no can't be blank, Username can't be blank.
     # ./spec/models/user_spec.rb:16:in `block (2 levels) in <top (required)>'

Finished in 0.2505 seconds
2 examples, 1 failure

【问题讨论】:

  • 我们需要模型知道你的错误在哪里。也许你使用 attr_accessible 或 attr_protected
  • @shingara 我已将用户模型粘贴到gist.github.com/1835904 我正在使用 attr_accessible

标签: ruby-on-rails ruby rspec mongoid


【解决方案1】:

您的问题是您通过#create 方法定义了一些数据,其中数据不是 attr_accessible 属性。

所以你可以在你的 attr_accessible 列表中添加这个属性,你可以通过示例避免使用批量分配:

  it "should create a new instance given a valid attribute" do
    u = User.new
    @attr.each do |k,v|
      u.send("#{k}=", v)
    end
    u.save!
  end

【讨论】:

  • 我使用了你提供的这个 sn-p 并且有这个错误:1)用户应该创建一个新实例给定一个有效的属性失败/错误:u.send(k“=”,v)NoMethodError:未定义的方法k' for #&lt;RSpec::Core::ExampleGroup::Nested_1:0x000000045fac18&gt; # ./spec/models/user_spec.rb:18:in block (3 级) in ' # ./spec/models/user_spec.rb:17:in each' # ./spec/models/user_spec.rb:17:in block (2 级) in ' 我评论了去掉模型中的 attr_accessible 行并且测试通过了,所以我知道在哪里看,我稍后会修复它,非常感谢
  • 对不起,我用send("#{k}=", v)修复了我的sn-p
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-07
  • 1970-01-01
  • 1970-01-01
  • 2014-02-11
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
相关资源
最近更新 更多