【问题标题】:Rspec and FactoryGirl.attributes_for params refactorRspec 和 FactoryGirl.attributes_for 参数重构
【发布时间】:2014-01-24 00:37:09
【问题描述】:

我目前正在让我的测试通过,但我想看看我是否可以用 let(:message) 或某种变量重构测试

邮件测试

 describe "Contact Form" do                                                                                                                         

    context "when a valid message" do                                                                                                                

      it "sends an email" do                                                                                                                         
        post contact_create_path, message: FactoryGirl.attributes_for(:message)                                                                      
        expect(ActionMailer::Base.deliveries.last.to).to eq(["#{ENV["MVP_USERNAME"]}"])                                                              
      end                                                                                                                                            
    end     

我要重构的部分是message: FactoryGirl.attributes_for(:message)。 我试图做类似的事情

context "when a valid message" do
    let(:message) { FactoryGirl.attributes_for(:message) }        
    it "sends an email" do                                                                                                                         
      post contact_create_path, message                                                                      
      expect(ActionMailer::Base.deliveries.last.to).to eq(["#{ENV["MVP_USERNAME"]}"])                                                              
    end 

但是输出 ActionController::ParameterMissing: param not found: message

其他尝试

@message = FactoryGirl.attributes_for(:message)

message = FactoryGirl.attributes_for(:message)

我可以这样离开它,但我觉得我应该出于某种原因对其进行更改。建议?

【问题讨论】:

    标签: ruby-on-rails unit-testing rspec factory-bot


    【解决方案1】:

    对我来说,它看起来不需要重构,但问题是您在 let 语句中的版本只是属性的散列。它缺少:message 键。

    let(:message) { message: FactoryGirl.attributes_for(:message) }
    

    这应该可行,但正如我所说,我认为您不需要重构它。实际上,我只是确保您将 FactoryGirl 语法方法混合到您的规范中,这样您就可以删除 FactoryGirl 并直接使用 attributes_for。

    在您的规范助手中:

    RSpec.configure do |config|
      config.include FactoryGirl::Syntax::Methods
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-30
      • 1970-01-01
      相关资源
      最近更新 更多